异常处理机制:
-
抛出异常
-
捕获异常
-
异常处理五个关键字
-
1.try:监控区域
-
catch:捕获异常
-
finally:处理善后工作
-
throw:制造异常
-
throws:抛出异常
try catch是遇到错误也能运行运行,throw 和 throws 是运行的时候给你抛出异常
-
//异常代码
package exception;
public class Text {
public static void main(String[] args) {
int a =1;
int b =0;
System.out.println(a/b);
}
}
//输出:(报错:零不能被除)
//Exception in thread "main" java.lang.ArithmeticException: / by zero
// at exception.Text.main(Text.java:8)
运用 try catch 捕捉异常,可以不要finally(在IO流以及一些资源中,关闭的方法都放在finally中)
//捕捉后 运行不报错
package exception;
public class Text {
public static void main(String[] args) {
int a =1;
int b =0;
//try catch是必须要的 finally可要可不要
try {//try监控区域
System.out.println(a/b);
}catch (Error e){//cath(想要捕获的异常类型) 捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally {//finally 处理善后工作 程序出不出异常都会执行
System.out.println("finally");
}
}
}
//输出:
//程序出现异常,变量b不能为0
//finally
快捷键:windo的是Ctrl+Alt+T Mac的是option+command+T
try {//try监控区域
System.out.println();
} catch (Exception e) {//cath 捕获异常
e.printStackTrace();//自动生成 打印错误的栈信息
} finally {
}
主动抛出异常 throw 和 throws
throw:制造异常
public class Text {
public static void main(String[] args) {
new Text2().text(1,0);
}
public void text(int a,int b){
if (b == 0) {//throw
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
//输出:Exception in thread "main" java.lang.ArithmeticException
// at exception.Text2.text(Text2.java:11)
// at exception.Text2.main(Text2.java:5)
throws:抛出异常
public class Text2 {
public static void main(String[] args) {
try {
new Text2().text1(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这方法中,处理不了这个异常,方法上抛出异常 抛到上一级
public void text1(int a,int b)throws ArithmeticException{
if (b == 0) {//throw
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
}
}
//输出:java.lang.ArithmeticException
// at exception.Text2.text1(Text2.java:21)
// at exception.Text2.main(Text2.java:6)