1.java中可以把异常当作对象来处理,并定义一个基类java.lang.Throwable
作为所有异常超类
2.在Java API中已经定义了许多异常类,这些异常类分为两大类
错误Error和异常Exception
3.异常处理机制:1)抛出异常 2)抓取异常
4.异常处理五个关键字:try、catch(捕获)、finally、throw、throws(抛出)
package 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(想要捕获的异常类型)最高捕获Throwable
System.out.println("程序异常,变量b不为0");
}finally {//一般处理善后工作
System.out.println("finally");
}
}*/
//finally可以不要
//想要捕获多个异常,范围得从小到大进行捕获
try {//try监控区域
if(b==0){//主动抛出异常 throw throws
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
}catch (Error e){//catch(想要捕获的异常类型)最高捕获Throwable
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception" );
}catch (Throwable t){
System.out.println("Throwable");
}
finally {//一般处理善后工作
System.out.println("finally");
}
}
}
package exception;
public class Test2 {
public static void main(String[] args) {
int a=1;
int b=0;
//快捷键:ctrl+Alt+t 选择中需要的代码就可以了
try {
System.out.println(a/b);
} catch (Exception e) {
System.exit(1);
e.printStackTrace();//打印错误的栈信息
} finally {
}
}
}
package exception;
public class Test3 {
public static void main(String[] args) {
//不用try catch,遇到异常就停止了,但用try catch捕获后,
// 程序遇到这个异常后还会继续执行,
//假设异常在意料之中,可以使程序不停止,继续往下走
try {
new Test3().test(1,0);
} catch (Exception e) {
e.printStackTrace();
}
}
//假设在方法中处理不了这个异常,就在方法上抛出异常 throws
public void test(int a,int b) throws ArithmeticException {
if(b==0){
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
}
}