1 什么是异常
2 简单分类
3 异常体系结构
最高是Throwable,其次是Error和Exception
3.1 Error
3.2 Exception
4 异常处理机制
抛出异常 捕获异常 异常处理五个关键字: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 ( "程序出现异常,变量b不能为0" ) ;
} finally {
System. out. println ( "finally" ) ;
}
}
}
package com. exception;
public class Test {
public static void main ( String[ ] args) {
int a = 1 ;
int b = 0 ;
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 void a ( ) {
b ( ) ;
}
public void b ( ) {
a ( ) ;
}
}
package com. exception;
public class Test2 {
public static void main ( String[ ] args) {
int a = 1 ;
int b = 0 ;
try {
System. out. println ( a/ b) ;
} catch ( Exception e) {
System. exit ( 1 ) ;
e. printStackTrace ( ) ;
} finally {
}
}
}
public class Test {
public static void main ( String[ ] args) {
try {
new Test ( ) . test ( 1 , 0 ) ;
} catch ( ArithmeticException e) {
e. printStackTrace ( ) ;
}
}
public void test ( int a, int b) throws ArithmeticException{
if ( b== 0 ) {
throw new ArithmeticException ( ) ;
}
}
}
5 自定义异常
package com. exception. demo02;
public class MyException extends Exception {
private int detail;
public MyException ( int a) {
this . detail = a;
}
@Override
public String toString ( ) {
return "MyException{" + "detail=" + detail + '}' ;
}
}
package com. exception. demo02;
public class Test {
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) ;
}
}
}
6 实际应用中的经验总结
写finally在IO流中有帮助(scanner)