×

Java Try-Catch Block

Java Try Block

The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a block that it means that throws the exception. This try block must and should be used in methods only.

The specific statements or code in a try block has been excepted when the remaining block of code is not executed. So, it is to be remembered that the code should not be kept in the try block so that it should no longer be an exception.

Syntax of try-catch in java language

try {    
//block of program that handles the exception
}catch (class_Name_ofException ref) {}    

Syntax of try-finally block in java language

try {    
//block of program handles the exception
} finally block {}    

Java Catch Block

The handling of the exception of the catch block in java programming language is done by verifying the type of exception depending on the given parameters. The exception which has been verified or initialize must be the parent class exception or generated exception type. Anyhow, declaring the generated exception type is a good approach.

Java try-catch: internal working

  1. Firstly, java virtual machine (JVM) will verify or check whether the given exception is handled or not.
  2. JVM gives a default value or default exception if exception is not handled.
  3. It also provides the default exception handler that works on the following tasks:
  4. Reprinting the exception description.
  5. Execute the stack trace (method of hierarchy where the exception occurs)
  6. Helps in terminating the program

After the exception there may be the presence of many lines of code that maybe 100 lines or more than it. Every code below the exception cannot be executed if the code is not handled.

Example 1

CatchEx1.java
public class CatchEx1 {  


    public static void main (String [] s) {  
        try  
        {  
        int i=80/0.
        }  
catch (e)  
        {  
            System.out.println(e).
        }  
        System.out.println("remaining of the code prints");
    }  


}  

Output:

remaining of the code prints

As Explained and shown from the above program, the remaining of the program is executed, i.e., the remaining of the code statement is printed.

Example 2

The program has been returned in a block that will not throw an exception.

CatchEx2.java
public class CatchEx2{  
    public static void main (String [] args) {  
        try  
        {  
        int d=110/0.
        System.out.println("remaining of the code");  
        }  
catch (ArithmeticException e)  
        {  
            System.out.println(e);  
        }  
    }  
      }

Output:

/ by zero

An exception occurs in the try block of the given code or program when the rest of the block code will not be printed or run.

Example 3

we will be using the parent class exception to handle the exception in this example.

CatchEx3.java
public class CatchEx3 {  


    public static void main (String [] s) {  
        try  
        {  
        int A=150/0.
catch (Exception e)  
        {  
            System.out.println(e);  
        }  
        System.out.println("remaining of the program is printed").
    }  


}  

Output:

remaining of the program is printed

Example 4

Here we have an example to modify the exception in a block of catch.

CatchEx4.java
public class CatchEx4 {  


    public static void main (String [] s) {  
        int k=400;  
        int l=0;  
        int data;  
        try  
        {  
        data=k/l.
        }    
catch (Exception e)  
        {  
             // the exception in catch blockis modifying or resolving
            System.out.println(k/l+2)).
        }  
    }  
}  

Output:

200

Example 5

From this example, consideration with try block, we also show exception code in a catch block.

CatchEx5.java
public class CatchEx5 {    
    public static void main (String [] s) {  
        try  
        {  
        int A1=500/0.
        }  
             // exception is handled
catch (Exception e)  
        {  
            // generating the exception in catch block  
        int A2=500/0; //may throw exception   


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

In this example the exception code is not written in the catch block. So, the code which is   in a try block and catch block can only handle the exceptions of that program.

Example 6

we maintain the given exception (Arithmetic Exception) with various types of exception class (ArrayIndexOutOfBoundsException-AIOOBException).

CatchEx6.java
public class CatchEx6 { 
    public static void main (String [] args) {  
        try  
        {  
int B=50/0.
        }  
catch (AIOOBException e)  
        {  
            System.out.println(e);  
        }  
        System.out.println("remaining of the code");  
    }  


}  

Example 7

An example to handle checked exception.

TryCatchEx7.java
import java.io. FileNotFoundException.
import java.io. PrintWriter.


public class TryCatchEx7{  


    public static void main (String [] args) {   
pw.
        try {  
            pw = new PrintWriter("jtp.txt").
pw. println("saved").
        }  
// checked exception handler by providing handling access
 catch (FileNotFoundException e) {  


            System.out.println(e).
        }         
    System.out.println("successfully file is saved").
    }  
}  

Output:

Successfully file is saved

Related Topics

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.