//类文件名名为jisuanqi,类名命名为"jisuanqi.java"
//分5步走
//1 用户自定义异常类型(注:需继承系统异常类其中之一)
//2 在方法名写出要抛出异常的类型
//3 在考虑出现的异常后面,throw异常对象
//4 在代码中出现异常的语句块用try检查
//5 捕捉异常后的处理(catch语句内处理),具体例子如下:
public class jisuanqi {
public static void main(String args[])
{
int a=(int)(Math.random()*10);
int b=(int)(Math.random()*10);
try //4检查异常块
{
SS k=new SS();
double c=k.jisuan(a, b);
System.out.print(c);
}
catch(chushu w)//5捕捉异常,格式为:异常类型 参数
{
System.out.println(w.getMessage());
}
}
}
class chushu extends Exception//1用户定义异常类型
{
chushu(String s)
{
super(s);
}
}
class SS
{
double jisuan(int a,int b) throws chushu//2在方法中,抛出异常类型
{
if(b==0) throw new chushu("异常:除数为0");//3抛出异常对象
else
{
double c=(double)(a/b);
return c;
}
}
}
Java用户自定义异常Exception处理
最新推荐文章于 2023-08-08 08:44:24 发布