异常
主要有三种类型的异常
- 检查型异常
- 运行时异常
- 错误error
捕获和抛出异常
异常处理五个关键字
- try、catch、finally、throw、throws
package com.exception;
public class test {
public static void main(String[] args) {
new test().test(1,0);
}
//假设这方法中,处理不能这个异常,方法上抛出异常
public void test(int a,int b)throws ArithmeticException
{
if (b==0){//throw throws
throw new ArithmeticException();//主动抛出异常,一般用在方法中使用
}
//System.out.println(a/b);
}
/**
try {//try监控区域
System.out.println(a/b);
}
//假设要捕获多个异常,catch范围从小到大
catch (Exception e){//catch(想要捕获的异常类型)捕获异常
System.out.println("程序运行出现异常,除数不能为0");
}catch (Throwable t){//catch(想要捕获的异常类型)捕获异常
System.out.println("程序运行出现异常,除数不能为0");
}
finally {
System.out.println("finally");
}
//finally 可以不要finally 一般用作善后工作
*/
}
package com.exception;
public class test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a/b);
} catch (Exception e) {
//System.exit(1);
e.printStackTrace();//打印错误的栈信息
} finally {
}
//ctrl+alt+t
}
}
自定义异常
实际应用中的总结:
- 处理运行时异常,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面,可以加一个catch(){Exception}来处理可能会被一楼的异常
- 尽量去处理异常,切忌只是简单地调用printStackTrace()来处理可能遗漏的异常
- print对于不确定的代码,也可以加上try-catch,处理潜在的异常
- 尽量添加finally语句块去释放占用的资源
package com.exception;
public class test3 {
//可能会存在异常的方法
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);
}
}
}
package com.exception;
//自定义的异常类
public class MyException extends Exception{
//传递数字>10;
private int detail;
public MyException(int a){
this.detail = a;
}
//toString异常的打印信息
@Override
public String toString() {
return "MyException{" + detail + '}';
}
}