Java Exceptions
An exception is an error that occurs while a program runs. A try and catch block handles the error so the program can continue.
Catch a divide by zero
The division raises ArithmeticException and the catch block runs. The line after the block prints as well.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
System.out.println("Program continues");
}
}finally runs after a success
The division succeeds and prints 5. The finally block still prints its line.
public class Main {
public static void main(String[] args) {
try {
int result = 20 / 4;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Division failed");
} finally {
System.out.println("Division checked");
}
System.out.println("Done");
}
}finally runs after a failure
The division fails and the catch block prints its line. The finally block prints after the catch block.
public class Main {
public static void main(String[] args) {
try {
int result = 20 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Division failed");
} finally {
System.out.println("Division checked");
}
System.out.println("Done");
}
}An uncaught exception stops the program
No try block guards this division. The program stops and the runtime prints the error report.
public class Main {
public static void main(String[] args) {
int total = 10;
int count = 0;
System.out.println(total / count);
}
}Example
public class Main {
public static void main(String[] args) {
try {
int result = 18 / 3;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Division failed");
} finally {
System.out.println("Check finished");
}
System.out.println("Program continues");
}
}Key points
- Code that may fail goes inside a try block.
- A catch block runs when the try block raises its exception type.
- A finally block runs whether the try block succeeds or fails.
- An uncaught exception stops the program and prints an error report.
- ArithmeticException is the exception raised by integer division by zero.
- getMessage returns the message stored in an exception.
In this example, the division succeeds and prints 6. The catch block is skipped because no exception occurs. The finally block prints Check finished. The last line then prints Program continues.
Note
A caught exception lets the lines after the block run as normal.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
Which block runs whether the try block succeeds or fails?