Java异常处理
- try
- catch
- finally
- throw
- throws
实际应用中的经验总结
- 处理运行时异常,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面,可以加一个catch(Exception)来处理可能被遗漏的异常
- 对于不确定的代码,也可以加上try-catch,处理潜在的异常
- 尽量去处理异常,切忌只是简单的调用printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去决定
- 尽量添加finally语句去释放占用的资源,例如IO、scanner等
通过代码来看一下使用方法
- try配合catch使用,finally可有可无
- catch不仅抛出异常,一个好的程序,需要可以处理异常
package com.huang.exception;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
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 { //处理善后操作,无论如何都会执行到这一步
System.out.println("finally");
}
}
}
以下是throw 和 throws的用法,用在方法内部或者外部
package com.huang.exception;
public class Demo02 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new Demo02().test(a,b);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
//主动抛出异常 throw throws
public void test(int a,int b) throws Exception {
if (b==0){
throw new Exception("除数不能为0");
}
}
}
自定义异常
自定义一个异常类,必须继承Exception
- 必须要继承Exception
- 需要重写toString方法,可以返回一些错误数值
package com.huang.exception;
//自定义异常
public class MyException extends Exception{
//一个数如果大于10 则抛出异常
private int detail;
public MyException(int a) {
this.detail = a;
}
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
main方法
package com.huang.exception;
public class Demo03 {
public static void main(String[] args) {
try {
test(12);
} catch (MyException e) {
System.out.println("MyException=>" + e);
} finally {
}
}
public static void test(int a) throws MyException{
if(a>10){
throw new MyException(a);
}
}
}