要理解Java异常处理是如何工作的,需要掌握以下三种类型的异常:
在Exception分支中有一个重要的子类RuntimeException(运行时异常)
这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生。
Error和Exception的区别:Error通常是灾难性的致命的错误,是程序无法控制和处理的,当出现这些异常时,Java虚拟机(JVM)一般会选择终止线程;Exception通常情况下是可以被程序处理的,并且在程序中应该尽可能的去处理这些异常
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域
System.out.println(a / b);
//}catch (ArithmeticException e){//catch 捕获异常
// System.out.println("算数异常");
} catch (Exception e){
System.out.println(e);
}finally {//处理善后工作
System.out.println("finally");
}//可以不要finally
}
}
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try catch 快捷键: Ctrl+alt+T
System.out.println(a / b);
} catch (Exception e) {
e.printStackTrace(); //打印错误信息
}
}
}
public class Test3 {
public static void main(String[] args) {
new Test3().test(1,0);
}
//假设这个方法中,处理不了这个异常,方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if (b==0) {//throw throws
throw new ArithmeticException();//主动的抛出异常
}
}
}
//自定义的异常类
public class MyException extends Exception{
//传递数字>10
private int detail;
public MyException(int detail) {
this.detail = detail;
}
//异常的打印信息
@Override
public String toString() {
return "MyException{"+detail+ "}";
}
}
public class Test {
//可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递参数为:" + a);
if (a>10) {
throw new MyException(a);//抛出 Alt + enter ,
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException:"+e);
}
}
}
本文章使用limfx的vscode插件快速发布