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异常
在调用者之中没处理编译可以过。
不过通过上面我们已经得知,如果不对可能的异常处理,会影响使程序异常时停止