Exception异常:软件程序在运行过程中,非常可能遇到的各种特殊情况。
异常发生在程序运行期间,它影响了正常的程序执行流程。
一般分为以下三种异常:
Java把异常当作对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类。
在Java API中定义了许多异常类,这些异常分为两大类,错误ERROR和异常Exception。
Error和Exception的区别:Error通常是灾难性的致命的错误,是程序无法控制和处理的,当出现这些异常时,Java虚拟机(JVM)一般会选择终止线程;Exception通常情况下是可以被程序处理的,并且在程序中尽可能的去处理这些异常。
抛出异常
捕获异常
异常处理五个关键字:try、catch、finally、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();
}
/*
//假设要捕获多个异常,从小到大
try { //监控区域
System.out.println(a/b); //ctrl+alt+t 快捷键
}catch (ArithmeticException e){ //catch(想要捕获的异常类型) 捕获异常,有try出现,必须有catch
System.out.println("程序出现异常,变量b不能为0");
e.printStackTrace(); //打印错误的栈信息
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}finally { //处理善后工作
System.out.println("finally");
}
*/
}
//假设这方法中,处理不了这个异常,方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if(b==0){ //throw throws
throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
}
}
}
使用Java内置的异常类可以描述在编程时出现的大部分异常情况。除此之外,用户还可以自定义异常类,只需继承Exception类即可。
public class Test {
//可能会存在异常的方法
static void test(int a) throws Demo01 {
System.out.println("传递的参数为:"+a);
if(a>10){
throw new Demo01(a);//抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (Demo01 e) {
//增加一些处理异常的代码
System.out.println("MyException=>"+e);
}
}
}
//自定义的异常类
public class Demo01 extends Exception{
//传递数字>10;
private int detail;
public Demo01(int a){
this.detail = a;
}
//toString:异常的打印信息
@Override
public String toString() {
return "Demo01{" +
"detail=" + detail +
‘}‘;
}
}
实际应用中的经验总结:
原文:https://www.cnblogs.com/xsyw/p/15208677.html