private static voidshow() { throw new UnsupportedOperationException(“抛出异常”); }
看下面这段代码有什么问题?php
public class SuperClass { public void start() throws IOException{ throw new IOException("Not able to open file"); } } public class SubClass extends SuperClass{ public void start() throws Exception{ throw new Exception("Not able to start"); } }
针对抛异常是IOException仍是Exception,能随便写吗,结合案例说一下?java
public static void start(){ System.out.println("Java Exception"); }
public static void main(String args[]) {
try{
start();
}catch(IOException e){
e.printStackTrace();
}
}git
- 上面的Java异常例子代码中,编译器将在处理IOException时报错,由于IOException是受检查异常,而start方法并无抛出IOException,因此编译器将抛出“异常,java.io.IOException不会在try语句体中抛出”,可是若是你将IOException改成Exception,编译器报错将消失,由于Exception能够用来捕捉全部运行时异常,这样就不须要声明抛出语句。我喜欢这样带有迷惑性的Java异常面试题,由于它不会让人轻易的找出是IOException仍是Exception。你也能够在JoshuaBloach和NeilGafter的Java谜题中找到一些有关Java错误和异常的具备迷惑性问题。
捕获异常时,为什么在catch中要注意异常层级关系?须要注意哪些问题?程序员
public static void start() throws IOException, RuntimeException{ throw new RuntimeException("Not able to Start"); }
public static void main(String args[]) {
try {
start();
} catch (Exception e) {
e.printStackTrace();
} catch (RuntimeException e2) {
e2.printStackTrace();
}
}github
- 这段代码会在捕捉异常代码块的RuntimeException类型变量“e2”里抛出编译异常错误。由于Exception是RuntimeException的超类,在start方法中全部的RuntimeException会被第一个捕捉异常块捕捉,这样就没法到达第二个捕捉块,这就是抛出“exception java.lang.RuntimeException has already been caught”的编译错误缘由。