异常处理的概念
1.异常也称之例外。是指程序在运行过程中会发生打断正常执行的集中情况
2.try需要检查的语句catch异常发生时需要处理的语句finally一定会执行到的代码
3.异常类的继承结构
Throws
-> Error
- Exception
->IOException
->RuntimeException
->ArithethicException
- IndexOutObBoundsException
->StringOutObBoundsException
->ArrayOutObBoundsException
抛出异常
1.程序中跑出异常
public class demo1 {
public static void main(String args[]) {
int a=4,b=0;
try {
if (b==0) {
throw new ArithmeticException("一个算数异常");
} else {
System.out.print(a+"/"+b+"="+a/b);
}
} catch (ArithmeticException e) {
System.out.print("抛出异常为"+e);
}
}
}
2.指定方法抛出异常,如果方法内的程序代码发生异常,且方法内没有捕捉异常的方法,我们可以将捕捉异常的try catch finally写在调用这个方法的程序代码内
public class demo1 {
public static void main(String args[]) {
demo1 demo = new demo1();
try {
demo.add(4,0);
} catch (Exception e) {
System.out.print("异常:"+e);
}
}
void add(int a,int b) throws Exception {
System.out.print(a+"/"+b+"="+a/b);
}
}
自定义异常类
1.为了处理各种异常,通过继承的方式编写自己异常,均继承自Exception。
public class DefaultException extends Exception {
public DefaultException(String msg) {
super(msg);
}
}
public class demo1 {
public static void main(String args[]) {
try {
throw new DefaultException("自定义异常");
} catch (Exception e) {
System.out.print("异常:" + e);
}
}
}