Java的异常(Exception)又称为例外,是一个程序执行期间发生的事件,或者超出程序员可控制范围,例如:用户破坏数据、试图打开一个不存在的文件等。为了能够及时有效的处理程序中的运行错误,Java中专门引入的异常类。
在学习过程中特别要注意Error与Exception的区别
try、catch、finally的用法 public class Exception {
public static void main(String[] args) {
try {
System.out.println(1/0);
}catch (ArithmeticException a){
System.out.println("程序出现异常");
}finally {
System.out.println("finally");
}
// 算数异常
}
}
输出
程序出现异常 finally
-
try:用于捕获异常。后面可接零个或多个catch块,如果没有catch块,则必须跟一个finally块。
-
catch;用于处理try捕获的异常。
-
finally:finally里面的语句都会执行。try或catch执行完遇到return之前,会执行一遍finally块。
Java 代码在编译过程中,如果受检查异常没有被 catch/throw 处理的话,就没办法通过编译 。
System.out.println(1/0);
报错内容
Exception in thread "main" java.lang.ArithmeticException: / by zero at OOP.Demo02.Exception.main(Exception.java:5)异常处理五个关键字
-
try、catch、finally、throw、thows
在方法中抛出用thow
package OOP.Demo02;
public class Exception {
public static void main(String[] args) {
try {
new Exception().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test (int a , int b) throws ArithmeticException {
throw new ArithmeticException(); //主动抛出异常,一般用在方法中
}
}
自定义的异常类
Java中Exception类中有很多已经写好的异常类,一般在自写的框架或系统中用到自定义异常。



