异常处理

61 阅读1分钟

异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)

  • Error:java虚拟机无法解决的严重问题。如:JVM系统内部错误,资源耗尽。比如StackOverflowError和OutOfMemoryError(简称:OOM)。一般不编写针对性代码。

代码演示:

public class ErrorTest{
public static void main(String[] args){ 
         main(args);    //栈溢出:java.lang.StackOverflowError     
}
public class ErrorTest{
public static void main(String[] args){ 
        Integer[] arr = new Integer[1024*1024*1024];    //堆溢出:java.lang.OutOfMemoryError    
}
  • Exception:其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。

1.空指针访问 2.试图读取不存在的文件 3.网络连接中断 4.数组角标越界

java.lang.Exception分为编译时异常(checked)和运行时异常(unchecked,RuntimeException)

编译时异常包括:IOException,FileNotFoundException,ClassNotFoundException

运行时异常包括:NullPointerException(空指针异常),ArrayIndexOutOfBoundsException(数组角标越界), ClassCastException(类型转化异常),NumberFormatException(编码格式异常),InputMismatchException (输入不匹配),ArithmeticException(算术异常)。