chu*_*hun 9 java exception-handling
谁能告诉我为什么这个类的输出是'xa'?
为什么不会捕获其他异常(RuntimeException和Exception)?
public class Tree {
public static void main(String... args) {
try
{
throw new NullPointerException(new Exception().toString());
}
catch (NullPointerException e)
{
System.out.print("x");
}
catch (RuntimeException e)
{
System.out.print("y");
}
catch (Exception e)
{
System.out.print("z");
}
finally{System.out.println("a");}
}
}
Run Code Online (Sandbox Code Playgroud)
pol*_*nts 16
public static void main(String[] args) {
new Exception();
System.out.println("Yippee!!");
// prints "Yippee!!"
}
Run Code Online (Sandbox Code Playgroud)
catch
条款,并不意味着被抓住了public static void main(String[] args) throws Exception {
try {
System.out.println("No math for me!");
} catch (ArithmeticException e) {
System.out.println("Math was wronged!");
} // prints "No math for me!"
}
Run Code Online (Sandbox Code Playgroud)
public static void main(String[] args) {
try {
throw new NullPointerException(args[-1]);
} catch (NullPointerException e) {
System.out.println("Ooops!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Ooh lala!!");
} // prints "Ooh lala!!"
}
Run Code Online (Sandbox Code Playgroud)
catch
从那里你扔的东西try
是public static void main(String[] args) throws Exception {
try {
args[-1] = null;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Gotcha!");
args[1/0] = null;
} catch (ArithmeticException e) {
System.out.println("You missed me!");
} // prints "Gotcha!"
} // Exception in thread "main" java.lang.ArithmeticException: / by zero
Run Code Online (Sandbox Code Playgroud)
finally
总是被执行public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("Oops!");
args[-1] = null;
} finally {
System.out.println("Yay!");
} // prints "Oops!", "Yay!",
} // Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
Run Code Online (Sandbox Code Playgroud)
finally
特朗普突然完成try/catch
static String greetings() {
try {
return "No mood!";
} finally {
return "Hey buddy!";
}
}
public static void main(String[] args) throws Exception {
System.out.println(greetings()); // prints "Hey buddy!"
try {
args[-1] = null;
} catch (ArrayIndexOutOfBoundsException e) {
throw new Exception("Catch me if you can!");
} finally {
throw new Exception("Yoink!");
}
} // Exception in thread "main" java.lang.Exception: Yoink!
Run Code Online (Sandbox Code Playgroud)
Yis*_*hai 12
抛出的唯一异常是throw语句旁边的异常.另一个是创建但不抛出.不可能同时抛出两个例外.
通常,当在另一个异常的构造函数中传递异常时,它指示该异常是该异常的原因.但是,实际抛出的唯一异常是throw语句旁边的异常.
在这种情况下,NullPointerException在其构造函数中不支持Exception,因为它不是由其他异常引起的,它是由null引用引起的.在其他情况下,这是因为在1.4之前没有在Java中引入异常链接,因此一些遗留异常类没有得到新构造函数的改编.在这种情况下,您可以使用该initCause(Throwable)
方法来执行构造函数的操作.
只会执行与抛出的异常类型匹配的第一个catch块.所以即使NullPointerException
是a RuntimeException
和a Exception
,它已经在那些块之前被捕获了.
如果颠倒catch块的顺序,则Exception
块将执行.(但不建议这样做.您应该始终按照最具体到最不具体的顺序放置catch块,如示例中所示.)
归档时间: |
|
查看次数: |
6157 次 |
最近记录: |