JAVA的异常
1. 程序在运行过程中遇到的意外,Exception,例如读取的文件不存在,网络参数问题,用户操作问题。
1)检查类异常,用户输入出乎意料之外。
2)运行时异常,代码编译时没有报错,程序运行时报错。是可能被程序员避免的异常。
2. 错误,error,JVM生成并抛出;Java虚拟机运行错误,VisualMachineError,当虚拟机不再有继续执行程序的资源时,抛出OutOfMemoryError;这些异常发生时,JVM一般会终止线程。NoClassDefFoundError,LinkageError这类错误不可查。
3. Throwable是所有Error和Exception的超类。
1)Error包含VisualMachineError和AWTError;VisualMachineError包含StackOverFlowError, OutOfMemoryError;
2)Exception包含IOException和RuntimeException;IOException包含FileNotFoundException和EOFException;RuntimeException包含ArrithmeticException, MissingResourceException, ClassNotFoundException, NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException, UnknowTypeException;
4. Error vs Exception:Error通常是灾难性错误,JVM一般会终止线程。Exception通常可以被程序处理,并且程序中应该尽量处理Exception。
5. try...catch...finally
package com.exception;
public class Application {
public static void main(String[] args) {
int a = 5;
int b = 0;
try{
System.out.println(a/b);
}catch (ArithmeticException e){
System.out.println("Get the ArithmeticException.");
}finally {
System.out.println("finally");
}
try{
new Application().a();
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}finally {
System.out.println("finally2");
}
try {
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public void a(){
b();
}
public void b(){
a();
}
}
6. throw vs throws, 方法定义时用throws表示方法可以抛出某种异常,在方法体中使用throw抛出异常。
package com.exception;
public class Application {
public static void main(String[] args) {
Application application = new Application();
try {
application.b(10, 0);
} catch (ArithmeticException e) {
System.exit(2);
} finally {
System.out.println("Finally");
}
}
public void b(int a, int b) throws ArithmeticException{
if(b == 0){
throw new ArithmeticException();
}
}
}
7. 自定义异常,继承Exception
public class Application {
public static void main(String[] args) {
try {
new Application().test(1,201);
} catch (MyException e) {
System.out.println(e);
//e.printStackTrace();
} finally {
System.out.println("Finally");
}
}
public void test(int a, int b) throws MyException{
if (b > 100){
System.out.println("b can't be Zero.");
throw new MyException(b);
}
}
}
package com.exception;
public class MyException extends Exception{
private int a;
public MyException(int a){
this.a = a;
}
@Override
public String toString() {
return "MyException{}" + a;
}
}

浙公网安备 33010602011771号