抛出异常与自定义异常
抛出异常
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);
} finally {
}
}
// 假设者方法中,处理不了这个异常,throws 方法 !上! 抛出异常 ,
public void test(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException();//主动抛出异常 throw一般在方法 !中!使用
}
}
}
/*
//如果要捕获多个异常:catch()需要从小到大书写
try {//try 监控区域
System.out.println(a/b);
}catch (Error e){//catch 捕获区域
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
}
finally {// 无论是否出现异常,都会执行finally,处理善后工作
//可以不使用 finally , 一般在IO流中,对一些资源进行释放、关闭
System.out.println("finally");
}
*/
public class Test02 {
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 MyException extends Exception{
// 传递数字 大于10 抛出异常
private int detial;
public MyException(int detial) {
this.detial = detial;
}
//toString:异常打印的消息
@Override
public String toString() {
return "MyException{" +
"detial=" + detial +
'}';
}
}
public class Test03 {
// 可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递的参数为:" + a);
if(a>10){
throw new MyException(a);
}else {
System.out.println("OK");
}
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException" + e);
}
}
}
处理运行时异常时,采用逻辑去合理规避同时辅助 try-catch 处理
在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
对于不确定的代码,也可以加上 try-catch,处理潜在的异常
尽量去处理异常,切忌只是简单地调用 printStackTrace()去打印输出
具体如何处理异常,要根据不同的业务需求和异常类型去决定
尽量添加finally语句块去释放占用的资源
浙公网安备 33010602011771号