异常处理
异常处理
-
抛出异常
-
处理异常
-
关键字:
- try 、catch 、 finally、 throw (手动方法中抛出异常)、throws(方法上抛出)
-
总结:
- 处理运行时异常时,采用合理逻辑合理规避同时辅助 try-catch 处理
- 在多重catch 块后面,可以加一个catch(Exception e)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try-catch ,处理潜在的异常
- 尽量去处理异常,切忌只是简单的调用 printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去决定
- 尽量添加finally 语句块去释放占用的资源 IO异常
package com.sxl.exception;
public class Test01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{ //监控区域
System.out.println(a/b);
}catch (ArithmeticException e){ //catch(要想捕获到异常类型)捕获异常
System.out.println("程序出现异常,不能被0 除");
}finally { //善后处理 //finally 可以不要;IO 资源关闭需要使用
System.out.println("finally");
}
}
}
package com.sxl.exception;
public class Test02 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//自动快捷键 command alt + t
//异常类型范围顺序 从小到大 类型:从低到高
try {
System.out.println(a/b);
} catch (Exception e) {
System.out.println("exception");
} catch (Error error) {
System.out.println(error);
} catch (Throwable throwable) {
System.out.println("throwable");
}
finally {
System.out.println("finally");
}
}
}
package com.sxl.exception;
public class Test03 {
public static void main(String[] args) {
try {
new Test03().test(1,0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void test(int a,int b) throws Exception{ //假如说方法处理不了异常,throws 在方法上抛出异常
if (b == 0){ //throw 主动抛出异常, 一般在方法中使用
throw new ArithmeticException();
}
System.out.println(a/b);
}
}

浙公网安备 33010602011771号