异常处理
* 1、
* try{
* 执行的代码
* 可能出现异常
* 一旦出现异常 系统自动我们创建一个异常类
* }catch(){
* 如果需要自己处理异常就catch
* 如果有多个异常 可以使用多个catch来捕获异常
* 如果有多个异常 catch的顺序是从子类到父类
*
* }finally{
* 不管有没有异常 finally都会被执行
* 处理资源回收 网络连接 数据库连接 I/O流
* }
*
* 如果异常出现 后面的代码将不会执行
* 所以try代码块 不要抓太多代码
int a = 1;
int b = 20;
FileReader fr = null;
try{
int c = b / a;
System.out.println("hello");
fr = new FileReader("d");
}catch (ArithmeticException e){
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
fr.close();
}catch (IOException e){
e.printStackTrace();
}
}
//圆括号里面只能添加可以关闭的对象
//实现了Closeable接口的对象
//如果出现异常 系统自动关闭这个资源
try (FileReader fr1 = new FileReader("dd")){
//使用对象
}catch (IOException e) {
e.printStackTrace();
}
2、使用throws抛出异常 给外部处理(最终还是以try catch处理)
class TException{
public static void test( ) throws FileNotFoundException {
FileReader fr = new FileReader("");
}
}
外部处理:
try {
TException.test();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
3.自己选择抛出异常 throw
public static void test2( )throws IllegalAccessException{
if (2>1){
throw new IllegalAccessException();
}
}
4.自定义异常类
class HYTException extends Exception{
//1.提供一个无参构造方法
public HYTException(){
}
//2.提供一个有参构造方法 参数是一个字符串
public HYTException(String desc){
super(desc);
}
}
public static void test3() throws HYTException {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
StackTraceElement e = stackTraceElements[2];
String detail = e.getFileName()+" "+e.getMethodName()+" "+e.getLineNumber();
throw new HYTException("自己的异常类 无所作为"+detail);
}
//4.
try {
TException.test3();
} catch (HYTException e) {
System.out.println(e.getMessage());
}