赞
踩
在Java语言中,将程序执行中发生的不正常情况称为“异常”。 (开发过程中的语法错误和逻辑错误不是异常)
异常主要分为编译时异常和运行时异常
java.lang.Throwable
|-----java.lang.Error:一般不编写针对性的代码进行处理。
|-----java.lang.Exception:可以进行异常的处理
|------编译时异常(checked)
|-----IOException
|-----FileNotFoundException
|-----ClassNotFoundException
|------运行时异常(unchecked,RuntimeException)
|-----NullPointerException
|-----ArrayIndexOutOfBoundsException
|-----ClassCastException
|-----NumberFormatException
|-----InputMismatchException
|-----ArithmeticException
运行时异常:是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常,对于此类异常一般不做处理
编译时异常:是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。
过程一:“抛”:程序正在执行的过程中,一旦抛出异常,就会在异常代码处生成一个对应的异常类对象 并将此对象抛出。
一旦抛出对象以后,其后的代码就不再执行。关于异常对象的产生:
①系统自动生成一个异常对象
②手动的生成一个异常对象,并抛出throw过程二:“抓”:可以理解为异常的处理方式:①try-catch-finally ② throws
使用的方式:
说明(理解很重要):
1.finally是可选的
2.使用try将可能出现的异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个异常类的对象,根据此对象的类型,去catch中进行匹配
3.一旦try中的异常对象对象匹配到某一个catch时,就会进入catch中进行异常处理,一旦处理完成,就跳出try-catch结构,继续执行其后的代码
4.catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓catch中的异常类型如果有子父类关系,则子类要声明在父类上面
5.常见的异常处理方式:
①getMessage() ②e.printStackTrace();
6.使用try-catch处理编译异常时,使得程序在编译时不报错,运行时还可能会报错, 相当于将一个编译时出现的错误,延时到运行时出现
7.try-catch-finally结构可以再次嵌套try-catch
在开发中,针对运行时异常一般不做处理,对于编译时异常使用try-catch-finally进行处理
使用样例:
public class ExceptionTest1 { public static void main(String[] args) { } //ArithmeticException 算术运算异常 @Test public void Test6() { try { int a = 10; int b = 0; System.out.println(a / b); }catch (ArithmeticException e){ e.printStackTrace(); } } @Test public void Test2(){ try{ File file = new File("hello.txt"); FileInputStream fis = new FileInputStream(file); int data = fis.read(); while(data != -1){ System.out.print((char) data); data = fis.read(); } fis.close(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } //NumberFormatException数据格式异常 @Test public void Test4() { String str = "123"; str = "abc"; try { int number = Integer.parseInt(str);//把字符串转为整型 }catch (NumberFormatException e){ // System.out.println("出现数值转换异常了"); e.printStackTrace(); System.out.println(e.getMessage());//获取异常信息 }catch (NullPointerException e){ System.out.println("出现空指针异常了"); }catch (Exception e){ System.out.println("出现异常了"); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。