То, что создано исключение, не означает, что оно выброшено
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!!"
}
Вы можете только 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
Практически при "всех" обстоятельствах,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!