w3resource

Java Exception Handling: Try-Catch block example

Java Exception Handling: Exercise-1 with Solution

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:

Flowchart: Java Exception  Exercises - Try-Catch block example.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/exception/java-exception-exercise-1.php