什么是异常
Exception 异常是指程序运行过程中出现了不期而至的各种状况
简单分类
检查性异常,程序员无法预见的 运行时异常 错误ERROR
异常体系结构
Java把异常当作为一个类来处理,,并定义了一个基类java.lang.Throwable作为所有异常的超类(父类) Error和Exception
Error
Error类对象由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关 Java虚拟机运行错误,JAM不再具有继续执行操作所需内存资源时,将会出现OutOfMemoryError。发生时,Java虚拟机线程终止
Exception
RuntimeException(运行时异常),编译无法通过,应从程序逻辑上避免 非运行时异常
异常处理机制
抛出异常 捕获异常 关键字:try、catch、finally、throw、throws
public class Test {
public static void main ( String [ ] args) {
int a = 1 ;
int b = 0 ;
try {
System . out. println ( a/ b) ;
} catch ( ArithmeticException e) {
System . out. println ( "程序出现异常,变量不能为0" ) ;
} finally {
System . out. println ( "finally" ) ;
}
}
}
try {
System . out. println ( a/ b) ;
} catch ( Error e) {
System . out. println ( "Error" ) ;
} catch ( Exception e) {
System . out. println ( "Exception" ) ;
} catch ( Throwable t) {
System . out. println ( "Throwable" ) ;
}
finally {
System . out. println ( "finally" ) ;
}
public static void main ( String [ ] args) {
try {
new Test ( ) . test01 ( 1 , 0 ) ;
} catch ( ArithmeticException e) {
e. printStackTrace ( ) ;
}
}
public void test01 ( int a, int b) throws ArithmeticException {
if ( b== 0 ) {
throw new ArithmeticException ( ) ;
}
}
自定义异常
自定义异常,继承Exception类即可 步骤;
创建自定义异常类 在方法中通过throw关键字抛出异常对象 通过try catch捕获
public class MyException extends Exception {
private int detail;
public MyException ( int a) {
this . detail = a;
}
@Override
public String toString ( ) {
return "MyException{" + detail + '}' ;
}
}
public class Test03 {
static void test ( int a) throws MyException {
System . out. println ( "传递的参数为" + a) ;
if ( a> 10 ) {
throw new MyException ( a) ;
}
System . out. println ( "OK" ) ;
}
public static void main ( String [ ] args) {
try {
test ( 11 ) ;
} catch ( MyException e) {
System . out. println ( "MyException=>" + e) ;
}
}
}
总结
处理运行异常时,采用逻辑去合理规避同时辅助try-catch 在多重catch块后面,可以加一个catch(Exception)来处理可能会遗漏掉的异常 对于不确定的代码块,加上try-catch,处理潜在异常 尽量去处理异常,切记加简单的输出异常 具体如何处理更具不同的业务需求而定 尽量添加finally语句块去释放占用的资源,IOScanner