一.初始Java异常
1、对异常的理解:异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)
2、Java程序在执行过程中所发生对异常事件可分为两类:
- Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError和OOM。一般不编写针对性 的代码进行处理。
- Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:
- 空指针访问
- 试图读取不存在的文件
- 网络连接中断
- 数组角标越界
3、运行时异常和编译时异常
运行时异常
- 是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。
- 对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响。
编译时异常
- 是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一 般性异常。编译器要求Java程序必须捕获或声明所有编译时异常。
- 对于这类异常,如果程序不处理,可能会带来意想不到的结果。
二.Error和Exception
1.Error
代码示例一:java.lang.OutOfMemoryError(堆溢出)
public class ErrorTest { public static void main(String[] args) { //堆溢出:java.lang.OutOfMemoryError Long[] arr = new Long[1024*1024*1024]; } }
运行结果:
代码示例二:java.lang.StackOverflowError(栈溢出)
public class ErrorTest { public static void main(String[] args) { //栈溢出:java.lang.StackOverflowError main(args); } }
运行结果:
2.Exception(运行时异常和编译时异常)
运行时异常
/* ******************以下是运行时异常*****************<i>本文来源gaodai$ma#com搞$代*码网2</i>* */ //ArithmeticException @Test public void test1(){ int num1 = 3; int num2 = 0; int num3 = 3 / 0; } //InputMismatchException @Test public void test2(){ Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); System.out.println(i); scanner.close(); } //NumberFormatException @Test public void test3(){ String str = "abcd"; int num = Integer.parseInt(str); } //ClassCastException @Test public void test4(){ Object obj = new Boolean(true); String str = (String)obj; } //IndexOutOfBoundsException @Test public void test5(){ ArrayIndexOutOfBoundsException Byte[] bytes = new Byte[3]; System.out.println(bytes[4]); } //NullPointerException @Test public void test6(){ int[] arr = null; System.out.println(arr[1]); }
编译时异常
/* ******************以下是编译时异常****************** */ @Test public void test7(){ File file = new File("a.txt"); //java.io.FileNotFoundException FileInputStream fis = new FileInputStream(file); //java.io.IOException int date = fis.read(); while (date != -1){ System.out.println((char)date); date = fis.read(); } fis.close(); }