×

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

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.