Типи даних і винятки в Java
Jim White
Java Developer
Exception і написати код для вирішення проблемиthrows до будь-якого методу, щоб передати виняток назад викликаючому методуthrows вкажіть список типів винятків, розділених комамиpublic static void someMethod() throws IndexOutOfBoundsException,
NegativeArraySizeException, NullPointerException {
// method code
}
Звичайний try-catch для обробки Exception
public static void main(String[] args) {
someMethod();
}
public static void someMethod(){
try {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
} catch (IndexOutOfBoundsException e) {
System.out.println(
"Ой — спроба отримати неіснуючий елемент");
}
}
Використання throws для обробки Exception
public static void main(String[] args) {
try {
someMethod();
} catch (IndexOutOfBoundsException e) {
System.out.println(
"someMethod намагався отримати неіснуючий елемент");
}
}
public static void someMethod()
throws IndexOutOfBoundsException {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
}

Exception можна «перекидати» даліmain зупинить застосунок
public class RethrowExample {
public static void main(String[] args) {
try {
method1(0);
} catch (ArithmeticException e) {
System.out.println("Ой — спроба некоректного ділення");
}
}
public static void method1(int divisor) throws ArithmeticException {
method2(divisor);
}
public static void method2 (int divisor) throws ArithmeticException {
int z = 5/divisor;
System.out.println(z);
}
}
Типи даних і винятки в Java