Java Exception Handling: Try-Catch block example
Throw and Catch Exception
Write a Java program that throws an exception and catch it using a try-catch block.
Sample Solution:
Java Code:
public class Exception_Example {
public static void main(String[] args) {
try {
int result = divideNumbers(5, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divideNumbers(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide the given number by zero!");
}
return dividend / divisor;
}
}
Sample Output:
Error: Cannot divide the given number by zero!
Explanation:
In the above exercise, the divideNumbers method takes two integers as input and checks if the divisor is zero. If the divisor is zero, it throws an ArithmeticException with the message "Cannot divide the given number by zero!"
In the main method, we call the divideNumbers method with 10 as the dividend and 0 as the divisor. Since the divisor is zero, it throws an exception. Using a try-catch block, we catch the exception and print the error message "Error: Cannot divide by zero".
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Java program to intentionally throw a custom exception from a method and catch it in the caller using a try-catch block.
- Write a Java program to manually throw a NullPointerException and catch it using multi-catch statements.
- Write a Java program where an exception is thrown inside a nested try block and re-thrown to be caught in an outer catch block.
- Write a Java program to throw different types of exceptions in a single try block and handle them separately using a multi-catch clause.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Java Exception Handling Exercises Home.
Next: Method to check and handle odd numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics