Is it possible to have multiple try blocks with only one catch block in java?


An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

Example

import java.util.Scanner;
public class ExceptionExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      int c = a/b;
      System.out.println("The result is: "+c);
   }
}

Output

Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)

Multiple try blocks:

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.

Example

The following Java program tries to employ single catch block for multiple try blocks.

class ExceptionExample{
   public static void main(String args[]) {
      int a,b;
      try {
         a=Integer.parseInt(args[0]);
         b=Integer.parseInt(args[1]);
      }
      try {
         int c=a/b;
         System.out.println(c);
      }catch(Exception ex) {
         System.out.println("Please pass the args while running the program");
      }
   }
}

Compile time exception

ExceptionExample.java:4: error: 'try' without 'catch', 'finally' or resource declarations
   try {
   ^
1 error

Updated on: 02-Jul-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements