异常
Error / Exception
Error
Error 类对象由 Java 虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关
Exception
在 Exception 分支中有一个重要的子类 RuntimeException (运行时异常)
- ArrayIndexOutOfBoundsException (数组下标越界)
- NullPointerException (空指针异常)
- ArithmeticException (算数异常)
- MissingResourceException (丢失资源)
- ClassNotFoundException (找不到类)
这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理
Error 和 Exception 的区别:Error 通常是灾难性的致命错误,是程序无法控制和处理的,当出现这些异常时,Java 虚拟机(JVM)一般会选择终止线程;Exception 通常情况下是可以被程序处理的,并且在程序中应该尽可能的去处理这些异常。
异常处理机制
抛出异常
捕获异常
异常处理五个关键字
- try
- catch
- finally
- throw
- throws
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常:从小到大
try { //try 监控区域
System.out.println(a/b);
}catch (Error e){//catch(想要捕获的异常类型) 捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}
finally {//处理善后工作
System.out.println("finally");
}
//finally 可以不要finally 假设IO,资源,关闭
}
}
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//Ctrl + Alt + T
try {
System.out.println(a/b);
} catch (Exception e) {
throw new RuntimeException(e);//打印错误的栈信息
} finally {
}
}
}
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
}
}
//假设方法中处理不了这个异常,则在方法上抛出异常
public void test(int a, int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException();//主动的抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
自定义异常
用户自定义异常类,只需继承 Exception 类即可
在程序中使用自定义异常类,可分为以下几个步骤:
- 创建自定义异常类
- 在方法中通过 throw 关键字抛出异常对象
- 如果在当前抛出异常的方法中处理异常,可以使用 try - catch 语句捕获并处理;否则在方法的声明处通过 throws 关键字指明要抛出给方法调用者的异常,继续进行下一步操作
- 在出现异常方法的调用者中捕获并处理异常
- 处理运行时异常时,采用逻辑去合理规避同时辅助 try - catch 处理
- 在多重 catch 块后面,可以加一个 catch (Exception) 来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上 try - catch,处理潜在的异常
- 尽量去处理异常,切忌只是简单地调用 printStackTrace() 去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去决定
- 尽量添加 finally 语句块去释放占用的资源
//自定义的异常类
public class MyException extends Exception{
//传递数字 > 10;
private int detail;
public MyException(int a) {
this.detail = a;
}
//toString
@Override
public String toString() {
return "MyException{" + "detail=" + detail + '}';
}
}
public class Test {
//可能会存在异常的方法
static void test(int a) throws MyException{
System.out.println("传递的参数为:" + a);
if (a>10){
throw new MyException(a);//抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
//增加一些处理异常的代码
System.out.println("MyException=>"+e);
}
}
}

浙公网安备 33010602011771号