Exception:
- 分为检查异常( 运行时异常 RuntimeException)
- 空指针异常
- 数组异常
- 类型转换异常
- 算数异常
2.非检查异常
- sql异常
- IO异常
捕获异常
try..catch..
try..catch…finnally…
public class TryCathTest{
public static void main(String[] args) {
TryCathTest tct=new TryCathTest();
// int result=tct.test();
// System.out.println("值为:"+result);
// int result2=tct.test2();
// System.out.println("我是test2");
int result=tct.test3();
System.out.println("我是test3,返回值:"+result);
}
public int test(){
int divider=10;
int result=100;
try{
while(divider>-1){
divider--;
result=result+10/divider;
}
return result;
}catch(Exception e){
e.printStackTrace();
System.out.println("发生了异常");
return -1;
}
}
public int test2(){
int divider=10;
int result=100;
try{
while(divider>-1){
divider--;
result=result+10/divider;
}
return result;
}catch(Exception e){
e.printStackTrace();
System.out.println("发生了异常");
return 999;
}finally{
System.out.println("我是final方法");
System.out.println("结果是:"+result);
}
}
public int test3(){
int divider=10;
int result=100;
try{
while(divider>-1){
divider--;
result=result+10/divider;
}
}catch(Exception e){
e.printStackTrace();
System.out.println("发生了异常");
}finally{
System.out.println("我是final方法");
System.out.println("结果是:"+result);
}
System.out.println("我是test3");
return 1111;
}
}
抛出异常
throw
throws
throws 在声明方法中使用
public class DrunkException extends Exception{
public DrunkException(){
}
public DrunkException(String message){
super(message);
}
}
throw 在方法体中使用 抛出一个异常对象
public class ExTest{
public static void main(String[] args) {
ExTest et=new ExTest();
et.test2();
}
//throws 在声明方法中调用
public void test1() throws DrunkException{
//throw 抛出一个异常对象
throw new DrunkException("喝酒不开车");
}
public void test2(){
try{
test1();
}catch(DrunkException e){
RuntimeException rex=new RuntimeException(e);
throw rex;
}
}
}