简单分类
异常体系结构
Error
Exception
抛出异常
捕获异常
异常处理五个关键字
package com.exception;
public class Demo02 {
public static void main(String[] args) {
int a = 0;
int b = 1;
try {// try监控区域
if (b==0){ // throw 和 throws不一样
throw new ArithmeticException();// 主动抛出异常
}
System.out.println(b/a);
}catch (Error e) {// catch(异常类型) 捕获异常
System.out.println("Error");
}catch (Exception t){
System.out.println("Exception");
}
catch (Throwable s){
System.out.println("Throwable");
}finally {// 处理善后工作
System.out.println("finally");
}
// finally 可以不写,一般用于:IO,资源,关闭!
}
}
package com.exception;
public class Demo03 {
public static void main(String[] args) {
int a = 0;
int b = 1;
//Ctrl + Alt + t:快捷键,获取异常
try {
System.out.println(b/a);
} catch (Exception e) {
e.printStackTrace();// 打印栈错误信息
} finally {
}
}
}
package com.exception;
public class Demo04 {
public static void main(String[] args) {
new Demo04().test(0,1);
}
// 假设这个方法中,处理不了这个异常,方式上抛出异常
public void test(int a, int b) throws ArithmeticException{
if (a==0){
throw new ArithmeticException();// 主动的抛出异常,一般在方法中适用
}
}
}
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=" + detail +
‘}‘;
}
}
package com.exception;
public class Test {
// 可能会存在异常的方法
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);
}
}
}
实际应用中的经验总结
原文:https://www.cnblogs.com/wcwblog/p/14648839.html