谁能告诉我为什么这个类的输出是'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");}
}
}
最佳答案
仅仅因为异常被创建,并不意味着它被抛出
public static void main(String[] args) {
new Exception();
System.out.println("Yippee!!");
// prints "Yippee!!"
}
只是因为有一个 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!"
}
异常可以在创建另一个异常时抛出
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!!"
}
你只能捕获
从你的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
实际上在“所有”情况下,总是执行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
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!
关于java - 关于多个 'catch'的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2788942/