一、捕捉异常
Java异常捕捉结构由try,catch,finally 3部分组成。
其中try语句块存放可能发生异常的Java语句
catch语句块在try语句之后,用来激发捕捉的异常
finally语句块是异常处理的最后执行部分,无论try语句块中的代码如何退出,都得执行finally语句块
Try{
\程序块
}
Catch(ExceptionType 1){ \匹配到Exceptiontype 1 得处理}
Catch(ExceptionType 2){ }
Catch(ExceptionType 3){ }
…………………
Catch(ExceptionType n){ \匹配到Exceptiontype n 得处理 }
Finally{ \程序块 }
/**
* @author 沈
* @create 2021-08-02
*/
public class Exception处理 {
public static void main(String[] args) {
Exce e = new Exce();
String i= null;
try {
i = e.qw(0);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(i);
NullPointerException e1=new NullPointerException("空指针");
System.out.println(e1.getMessage());
}
public static class Exce extends Exception {
private int ara;
public int getAra() {
return ara;
}
public void setAra(int ara) {
this.ara = ara;
}
public Exce(int ara) {
this.ara = ara;
}
public Exce() {
}
public String qw(int ara)throws Exception{
if (ara==0){
new Exception("ara=0");
return "错误0";
}else{
return "正确";
}
}
}
}