目的
了解异常处理并知道其运用,使用
主要内容
异常处理 Exception 处理运行过程中出现的不可控的错误 使程序更健壮
try{
执行的代码
可能出现的异常
一旦出现异常 系统自动为我们创建一个异常对象并抛出
}catch(NullPointerException e){
如果需要自己处理异常就catch
}catch(Exception e){
如果有多个异常 可以使用catch来捕获
如果有多个异常 catch的顺序是从小到大
}catch(Exception1 e){
}finally{
不管有没有异常finally都会被执行
处理资源回收 网络连接 数据库连接 I/O流
}
1.处理异常的方式
pubilc class Exception{
public static void main(String[] args){
int a=0;
int b=20;
FileReader fr=null;
//1.try{}catch()
try{
int c=b/1;
System.out.println("java");
fr=new FileReader("");
}catch (ArithmeticException e){
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
// 2.自己写或者Alt+Enter让系统抛出
fr.close();
}
}
}
class TException{
//使用throws抛出异常
public static void test() throws FileNotFoundException,NullPointerException{
FileReader fr=new FileReader("");
}
}
如果异常出现,那么try代码块后面的代码不会执行
try尽量不要捕获太多异常
使用throws抛出异常,给外部处理
2.自己定义一个抛出异常类
public class Exception1 {
public static void main(String[] args) throws IOException {
FileReader fr=null;
//括号里面只能添加可以关闭的对象
//实现Closeable接口对象
//如果出现异常 系统自动关闭这个资源
try(FileReader fr1=new FileReader("aaa")){
//使用对象
}catch(IOException e){
e.printStackTrace();
}
try {
TException.test();
}catch (IOException e){
System.out.println(e.getMessage());
}
try {
TException.test3();
} catch (ZRException e) {
System.out.println(e.getMessage());
}
}
}
class TException{
//使用throw抛出一个自己创建的异常
public void test2() throws IllegalAccessException {
if (2>1){
throw new IllegalAccessException();
}
}
}
//自己定义的抛出异常类的方法
public static void test3() throws ZRException{
StackTraceElement[] stackTrace=Thread.currentThread().getStackTrace();
StackTraceElement e = stackTrace[2];
String detail = e.getFileName()+"->"+e.getMethodName()+"->"+e.getLineNumber();
throw new ZRException("自己的异常类:无所作为 "+detail);
}
}
// 2.自己定义一个抛出异常类
class ZRException extends Exception{
//1.提供一个无参构造方法
public ZRException(){
}
//2.提供一个有参构造方法 参数是一个字符串
public ZRException(String desc){
super(desc);
}
}
当特殊情况出现了,自己可以选择抛出异常
自定义异常类