—异常与错误:
Throwable是错误(Error)与异常(Exception)的父类
异常是不正常的事件,不是错误。
异常与错误的区别:
异常(exception)可以通过程序回复
错误(error)是程序无法解决的
—异常分为RuntimeException异常和CheckedException异常:
程序运行期抛出的异常且所有RuntimeException的子类都是运行期异常。
例如:
NullPointerException ===> 空指针异常
ArithmeticException===>算术错误情形,如10/0;
ArrayIndexOutOfBoundsException===>数组大小小于或大于实际的数组大小
ClassCastException===>不能加载所需的类
除去运行期异常都是检测异常
例如:
IOException===>I/O 异常的根类
SqlException
运行时异常不会引起编译报错,不需要强制处理
检查异常时会引起编译报错,所以需要强制处理
—异常中一些关键字的用法:
try catch finally的用法
try:
检测不安全的代码块
try块中任何一条语句发生了异常,下面的代码将不会被执行,程序将跳转到异常处理代码块中,即catch块。因此,不要随意将不相关的代码放到try块中,因为随时可能会中断执行
catch:
把抓到的类型匹配的异常捕获,保证程序能继续运行下去
catch语句必须紧跟着try语句之后,称为捕获异常,也就是异常处理函数,一个try后面可以写多个catch,分别捕获不同类型的异常,要从子类往父类的顺序写,否则有编译错误,try后面也可以没有catch语句
finally:
finally该内容总是会执行的,只能有一个finally语句
try后面也可以没有finally语句
用法如下:
try{ 可能会发生异常的代码 }catch(异常类型 引用名){ 异常处理代码 }finally{ 必须执行的代码 }finally与return
不管是在正常代码和异常处理代码中return,都会先执行finally再return
是否出现异常都会执行finally
在使用System.exit(0)时就不会执行finally
例子:
public static void main(String[] args) {
try{ System.out.println("try"); int m=10/0; return; }catch(ArithmeticException e){ System.out.println("catch"); return; } finally{ System.out.println("finally");}输出结果为:try、catch、finally
try{ System.out.println("try"); System.exit(0); int m=10/0; return; }catch(ArithmeticException e){ System.out.println("catch"); return; } finally{ System.out.println("finally"); } }输出结果为:trythrow和throws,层层抛出
throw:
用于抛出异常
抛出异常后处理:
使用try-catch处理
使用throws声明异常,一层一层的往上抛,也要使用try-catch处理
例子:
public class ElevatorException extends Exception{
public ElevatorException() { super(); } public ElevatorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ElevatorException(String message, Throwable cause) { super(message, cause); } public ElevatorException(String message) { super(message); } public ElevatorException(Throwable cause) { super(cause); } public class ThrowThrows { public static void main(String[] args) { try{ text1(); }catch(ElevatorException h){ h.printStackTrace(); } } private static void text1() throws IOException,ElevatorException{ text(); } //一层一层往上抛 private static void text() throws IOException,ElevatorException{ throw new ElevatorException(); }throws
用于方法上,指出方法引发的异常,就如以上的例子,若该异常为CheckedException 则调用该方法时需要对此进行处理。
可以声明多种异常类型,用逗号分开即可。
public void test throws 异常1,异常2,异常3{}子类覆盖父类,子类不能声明抛出父类范围更大的异常方法
层层抛出:就是 catch中,再次用throw抛出异常如下:
public class App { public static void main(String[] args) {
try{ test(); }catch(BusinessException n){ n.printStackTrace(); } } private static void test() throws BusinessException{ try{ test1(); }catch(TemperatureOverHighException e){ throw new BusinessException(e); } } private static void test1() throws TemperatureOverHighException{ throw new TemperatureOverHighException(); }}