ADVERTISEMENT
ADVERTISEMENT

Java program to implement the try block with multiple catch blocks

Java example to implement the try block with multiple catch blocks.
Submitted by Nidhi, on April 19, 2022

Problem Solution:

In this program, we will create a try block to check exceptions and create multiple catch blocks to handle exceptions.

Program/Source Code:

The source code to implement the try block with multiple catch blocks is given below. The given program is compiled and executed successfully.

// Java program to implement the try block 
// with multiple catch blocks

public class Main {
  public static void main(String[] args) {
    try {
      String str = null;

      int len = str.length();

      System.out.println("Length of string: " + len);
    } catch (NullPointerException e) {
      System.out.println("Exception1");
    } catch (RuntimeException e) {
      System.out.println("Exception2");
    } catch (Exception e) {
      System.out.println("Exception3");
    }

    System.out.println("Program Finished");
  }
}

Output:

Exception1
Program Finished

Explanation:

In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.

Here, we created a try block to check exceptions in the source code and defined multiple catch blocks to handle exceptions and print appropriate messages.

Java Exception Handling Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.