其中Exception及其子类(不包括RuntimeException)是必须捕获的异常
Error及其子类,RuntimeException及其子类是不需要捕获的
异常名 | 解释 | |
---|---|---|
VirtualMachineError | 虚拟机异常 | |
ReflectionError | 反射异常 | |
Error | ||
IOException | IO流异常 | |
DataFormatException | 日期格式日常 | |
Exception | ||
ArithmeticException | 算术异常 | |
IndexOutOfBoundsException | 下标越界 | |
NullPointerException | 空指针 | |
ClassCastException | 类型转换异常 | |
RuntimeException |
捕获
try catch finally,把要捕获异常的语句放到try里面
public static void main(String[] args) { try { ExceptionTwo(); //会发生算数异常 System.out.println("try"); }catch (RuntimeException e) { System.out.println("run"); e.printStackTrace(); //打印方法调用栈 } catch (Exception e) { System.out.println("ex"); }finally{ System.out.println("finally"); } System.out.println("我是异常下面的语句"); } static void ExceptionTwo() { ExceptionOne(); } static void ExceptionOne() { int a = 1/0; //算数异常 }
run java.lang.ArithmeticException: / by zero at exception.Test.ExceptionOne(Test.java:36) at exception.Test.ExceptionTwo(Test.java:31) at exception.Test.main(Test.java:11) finally 我是异常下面的语句
抛出
throws在方法声明中抛出,throw在方法体内抛出
当某个方法抛出异常时,如果当前方法没有捕获,异常就会被抛到上层调用方法,直到遇到某个try ...catch被捕获为止
创建异常一般使用匿名函数方式
public static void main(String[] args) { try { ExceptionOne(); //这里被向上抛出的异常需要捕获,或者继续向上抛出 } catch (FileNotFoundException e) { e.printStackTrace(); } } static void ExceptionOne() throws FileNotFoundException { File file = new File("D:test.txt"); FileOutputStream fs = new FileOutputStream(file);//会抛出文件异常,但在方法声明中用了throws向上抛出 }
public static void main(String[] args) throws Exception { int a = 1; if (a < 2){ throw new Exception("a小于2了"); //一般继承Exception,然后使用构造函数 } }
打印
public class Test { public static void main(String[] args) { Logger logger = Logger.getLogger(Test.class); try { int a = 1/0; //会发生算数异常 }catch (RuntimeException e) { logger.error("测试异常",e); // 使用log4j日志系统 } } }
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句