1.异常结构图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2b63577c9221c7633c51646396fca60a.png)
2.try-catch-finally捕获异常
try{
System.out.println(a/b);
}catch (ArithmeticException e){
System.out.println("程序出现异常,除数不能为0");
}finally{
System.out.println("finally");
}
try{
System.out.println(a/b);
}catch(Error e){
System.out.println("error");
}catch (Exception e){
System.out.println("exception");
}catch (Throwable t){
System.out.println("throwable");
} finally{
System.out.println("finally");
}
}
3.抛出异常throw/throws
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException();
}
}
}
4.自定义异常
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7bca5cf9c4867aec5c3397ea03f128c5.png)
public class MyException extends Exception {
private int detail;
public MyException(int a) {
this.detail = a;
}
@Override
public String toString() {
return "MyException{" +"detail=" + detail +'}';
}
}
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);
}
}
}
5.总结
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/420f7c8801513ebb9e8b92ff94aeb02c.png)