public class ExceptionDemo {
public static void main(String[] args) throws ArithmeticException{
/*
* 需求:一个除数为0的异常处理方式。
* 方式一:在函数上声明抛出。告诉调用者可能会出现异常。
*/
Demo d = new Demo();
int x = d.div(4, 0);
System.out.println("x="+x);
System.out.println("over");
}
}
//自定义一个类,这个类中有个方法,进行除法运算。
class Demo{
int div(int a,int b)throws ArithmeticException{//抛出,谁掉用抛给谁。
return a/b;
}
}
异常处理方式二:进行捕捉处理。
public class ExceptionDemo2 {
public static void main(String[] args) {
try{
Demo2 d = new Demo2();
d.div(4, 0);
}
//异常处理方式。
catch(ArithmeticException e){
System.out.println("message:"+e.getMessage());//打印信息。
// System.out.println("toString:"+e.toString());//异常的名字+信息。
// System.out.println("啊,异常啦");
// e.printStackTrace();//打印异常的信息+名字+位置。
}
System.out.println("over");
}
}
class Demo2 {
int div(int a,int b)throws ArithmeticException{
if(b==0)
throw new ArithmeticException("完了,被零除了");
return a/b;
}
}
自定义异常:
public class ExceptionDemo3 {
public static void main(String[] args) {
/*
* 需求:自定义除数不能为负数的异常。
* 定义方式:
* 1、定义一个类,对异常问题进行描述。
* 2、必须让这个类继承异常类,具备可抛性。
*/
try{
Demo3 d = new Demo3();
int num = d.div(4, -1);
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("message="+e.getMessage());
}
catch(FuShuException e){
System.out.println("message="+e.getMessage());
System.out.println("toString:"+e.toString());
System.out.println("负数是:"+e.getNum());
e.printStackTrace();
}
}
}
//描述负数异常。
class FuShuException extends Exception{
private int num;
FuShuException()
{
super();
}
FuShuException(String message){
super(message);//将异常信息传给父类处理。
}
FuShuException(int num){
this.num = num;
}
public int getNum(){
return num;
}
}
//两个整形数的除法运算。
class Demo3{
int a,b;
int div(int a,int b)throws ArithmeticException,FuShuException {
if(b<0)
throw new FuShuException(b);
// throw new FuShuException("错误,不允许除数为负数。。");
if(b==0)
throw new ArithmeticException("除数为零了。。");
return a/b;
}
}