Error和Exception的区别:Error通常是灾难性的致命的错误,jvm会选择终止线程;Exception通常是可以被程序处理的。
package Jc;
public class A {
public static void main(String[] args) {
int a = 1, 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 t) {
System.out.println("Throwable");
} finally { //处理善后共工作
System.out.println("finally");
}
//finally try-catch-finally(可以不要finally,假设IO,资源,关闭)
}
//ctrl+alt+t:快捷键生产try-catch-finally
}
throw制造异常,throws抛出异常
package Jc;
public class A {
public static void main(String[] args) {
try {
new A().test(1,0);
}catch (ArithmeticException e){
e.printStackTrace();
}
}
public void test(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
}
}
}
自定义异常
package Jc;
class MyException extends Exception{
private int detail;
public MyException(int a){
this.detail=a;
}
@Override
public String toString(){
return "MyException{"+detail+‘}‘;
}
}
public class A {
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/junun/p/15116420.html