Can we have a try block without a catch block in Java?

By IncludeHelp Last updated : February 4, 2024

Yes. We can have a try block without a catch block in Java.

You can use the finally block instead of the catch block which executes before the ending of the program, you can place your important closing statements there.

Example of a try block without having a catch block in Java

This example demonstrates a try block without having a catch block.

// Example of a try block without having 
// a catch block in Java
public class Main {
  // The main() method
  public static void main(String args[]) {
    try {
      System.out.println("Hello, World!");
      System.out.println("Try block body");
    } finally {
      System.out.println("Bye! This is a finally block.");
    }
  }
}

Output

The output of the above example is:

Hello, World!
Try block body
Bye! This is a finally block.

Another Example

This example demonstrates a try block without having a catch block. In this example, we are dividing a number by 0.

// Example of a try block without having 
// a catch block in Java
public class Main {
  // The main() method
  public static void main(String args[]) {
    int a = 10;
    int b = 0;
    
    try {
      double result = a / b;
      System.out.println("Result is : " + result);
    } finally {
      System.out.println("Bye! This is a finally block.");
    }
  }
}

Output

The output of the above example is:

Bye! This is a finally block.
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.main(Main.java:10)
 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.