Back to: Java Tutorials
Throwing and catching exceptions in Java is a fundamental part of Java Exception Handling. The throw
statement is used to throw an exception, and the try
–catch
block is used to catch and handle exceptions.
Here’s an example that demonstrates throwing and catching an exception:
public class Example {
public static void main(String[] args) {
try {
int x = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e);
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
}
In this example, the divide
method throws an ArithmeticException
if the second argument b
is 0. The main
method calls the divide
method with arguments 10 and 0, which causes an ArithmeticException
to be thrown. The try
–catch
block in the main
method catches the exception and prints a message to the console.
The output of the above code will be:
Caught exception: java.lang.ArithmeticException: Cannot divide by zero
Here’s a breakdown of the code:
- The
divide
method takes two argumentsa
andb
. - If
b
is 0, thedivide
method throws anArithmeticException
with the message “Cannot divide by zero”. - The
main
method calls thedivide
method with arguments 10 and 0. - The
try
–catch
block in themain
method catches theArithmeticException
that was thrown by thedivide
method and prints a message to the console.
🗒 Note:
It’s important to note that not all exceptions need to be caught. If an exception is not caught, it will propagate up the call stack until it is caught by a higher-level exception handler or the program terminates. In the example above, if the ArithmeticException
was not caught in the main
method, it would propagate up the call stack until it was caught by the JVM or the program terminated.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media
Follow Author