异常
异常(Exception)
1.异常处理机制
- 抛出异常
- 捕获异常
- 异常处理的五个关键字
- try、catch、finally、throw、throws
package com.exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0);
} catch (Exception e) {
e.printStackTrace();
}
//finally 可以不要finally,假设IO,资源,关闭!
}
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 (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");
}
*/
快捷键:
package com.exception.demo01;
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) {
e.printStackTrace(); //打印错误的栈信息
} finally {
}
}
}
2.自定义异常
package com.exception.demo02;
//自定义的异常类
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 +
'}';
}
}
测试类:
package com.exception.demo02;
public class Test {
static void test(int a) throws Exception{
System.out.println("传递的参数为:"+a);
if(a>10){
throw new MyException(a);//抛出
}
System.out.println("ok");
}
public static void main(String[] args) {
try {
test(1);
} catch (Exception e) {
//增加一些处理异常的代码块
System.out.println("MyException=>"+e);
}
}
}
实际应用中:
- 处理运行时异常,采用逻辑去合理规避同时辅助try - catch处理
- 在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try - catch,处理潜在异常
- 尽量去处理异常,切忌只是简单的调用printStackTrace()去打印
- 尽量添加finally语句块去释放占用的资源

浙公网安备 33010602011771号