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

By IncludeHelp Last updated : February 4, 2024

No. You cannot have a try block without a catch or finally block in Java.

A try block must have either a catch or a finally block. If you do not use catch or finally, code will generate an error "'try' without 'catch', 'finally' or resource declarations".

You must use either a catch or finally block with a try block.

Example of a try block without catch or finally block

// Example of a try block without having 
// a catch or finally 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");
    }
  }
}

Output

The output of the above program is:

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

Another Example

// Example of a try block without having 
// a catch or finally 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);
    }
  }
}

Output

The output of the above program is:

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

Comments and Discussions!

Load comments ↻






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