×

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has always been run. Even the Prior execution or printing statements of the program is given we cannot know whether an exception happens or not to implement necessary statements are not.

The try-catch block is executed after the try block is implemented or executed.

Block Flow Chart:

Java Try Keyword

In the same manner that Java's final is a reserved keyword, try is also a reserved keyword that cannot be used as an identifier. Try, keyword ensures that a part of code will be run even if an exception is thrown when used in combination with a try/catch block. The control of the program to its source before the try and catch blocks are executed then last block will be executed.

Note: The JVM will implement or execute the finally block before terminating or stopping the application (if any), if we don’t handle the exception.

Usage of Try Block in Java

In Java programming language, "cleanup" code, such as terminating a file or a connection, can be inserted in the finally block. As part of programming specifications, we interface with databases by creating connections, using input and output streams, and resources inside a try block. It is advisable to use the finally block together with try-catch blocks as a good programmer to ensure the safety of resources and to make sure that there is no resource leak as part of our software.

The try block is where you can print the essential statements.

Usage of Try Java keyword

Let's understand and examine the various scenarios in which the Java finally block can be applied and implemented.

Case 1: In the absence of an exception

Let's look at the example below, where the Java program doesn't raise any exceptions and the finally, block is executed following the try block.

TestFinallyBlock.java


class Fnl_Block {    
  public static void main (String s []) {    
  try {    
// any exception is not thrown in the above code
   int ja=25/5;
   System.out.println(ja);
  }    
//executed without regard to exception happened or not
  catch (NullPointerException e) {  
System.out.println(e);
}    
 finally {  
System.out.println("Ececution of the finally block is always done.");
}    


System.out.println("remaining of the code...");
  }    
}    

Output:

Java try block

Case 2: A catch block is not used when an exception occurs.

In this case, the catch block is unable to handle the exception when the code throws exception statements. Excepting this, the program terminates improperly or irregularly after the try block is executed after the running of try block.

public class Fnl_block_1{    
      public static void main (String s []) {   
      try {    
        System.out.println("inner of try block");


        //The code below raises the divide-by-zero exception.
       int ja=25/0;
       System.out.println(ja);
      }    
//cannot handle exception of the arithmetic type
//can only accept exceptions of the Null Pointer type.
      catch (Null_Pointer_Exptn e) {  
        System.out.println(e);
      }   
//checking whether an exception has occurred is executed or not.
      finally {  
        System.out.println("Execution of the finally block is always done");
      }    


      System.out.println("remaining of the code...");
      }    
    }    

Output:

Java try block

Case 3: When a catch block is used to handle an exception that arises

Example:

Let's look at the example below, where the catch block handles an exception that the Java code throws. After the block of try-catch, the try block is then run. Additionally, the remaining code runs normally as well.

public class Fnl_Block_2{    
      public static void main (String s []) {
      try {    
        System.out.println("Inner side of try block");


        //below code throws divide by zero exception  
       int ja=25/0;
       System.out.println(ja);
} //handles the Arithmetic Exception 
            // Divide by zero


      catch (Arithmetic_Exception e) {  
        System.out.println("Exception handled");
        System.out.println(e);
      }   


      //regardless of whether an exception has occurred, /executes
      finally {  
        System.out.println("Execution of the final block is always done");
      }    


      System.out.println("remaining of the codeexecuted...");
      }    
    }  

Output:

Java try block

Rule: There may be zero or more catch blocks for each attempt block, but there may only be one try block.

Note: If the application terminates (either by calling System.exit() or by introducing a fatal error that causes the procedure to return), there they won't be carried out bt finally keyword.


Related Topics

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.