java异常处理

1、

public class ThrowsException {

static void demo(){
throw new NullPointerException("demo");//运行时错误
}

public static void main(String args[]){

demo();

System.out.println("fdjsalfjdls");
}

}

结果:编译可过,但是运行时

Exception in thread "main" java.lang.NullPointerException: demo
at excep.ThrowsException.demo(ThrowsException.java:8)
at excep.ThrowsException.main(ThrowsException.java:17)

由于未处理该异常,未执行System.out语句

2、

public class ThrowsException {

static void demo(){
throw new NullPointerException("demo");
/*try{throw new FileNotFoundException();
}
catch(FileNotFoundException e){

}*/
}

public static void main(String args[]){
try{
demo();
}
catch(NullPointerException e){
System.out.println(e);
}


System.out.println("fdjsalfjdls");
}

}

运行结果:

java.lang.NullPointerException: demo
fdjsalfjdls

3、检查异常

public class ThrowsException {

static void demo(){
try{throw new FileNotFoundException();
}
catch(FileNotFoundException e){
System.out.println(e);
}
}

public static void main(String args[]){
demo();
System.out.println("fdjsalfjdls");
}

}

运行结果:

java.io.FileNotFoundException
fdjsalfjdls

4、当试图对检查异常(非运行时)这样处理时,编译不过,有两处error

public class ThrowsException {

static void demo(){
//throw new NullPointerException("demo");
throw new FileNotFoundException();//Unhandled exception type FileNotFoundException
}

public static void main(String args[]){
try{
demo();
}catch(FileNotFoundException e){         //Unreachable catch block for FileNotFoundException.
System.out.println(e);                      // This exception is never thrown from the try statement body
}
System.out.println("fdjsalfjdls");
}

}

eclipse提供的解决办法如下

对于error1,可以【添加try……catch……】或者【声明抛出异常】

如果采用后者static void demo() throws FileNotFoundException{
//throw new NullPointerException("demo");
throw new FileNotFoundException();
}

由于该异常是检查异常,在调用者main()方法中,try catch语句反而变得必须了

3、为了进一步验证,我在被调用者声明抛出ArrayIndexOutOfBoundsException异常

在调用者之中没处理编译可以过。

不过通过上面我们已经得知,如果不对可能的异常处理,会影响使程序异常时停止





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值