Try Catch Block in Java

Try Catch Block in Java

In this article we will be discussing about Try Catch Block in Java.

An Exception occurs when java compiler finds any error or exception in the program that can be occur due to mistake in the code by programmer or for any other reason.

Try Catch Block in Java

Try Block:

All the code that is to be tested in the program is to be contained in the try block. Try block executes all the code and if exist, It passes the exception to the catch block.
The try block’s remaining statements won’t run if an exception arises at that specific statement. Therefore, it is advised against keeping code in a try block that won’t throw an exception.

Syntax:

try{
    // Block of code
}

Catch Block:

All the code that is executed in the try block. if it shows any type of exception will be thrown to the catch block. It is used to handle the Exception by declaring the type of exception within the parameter.
Only after the try block, The catch block Should be used. You can use multiple catch block with a single try block.

Syntax:

Catch{
    // Block of code
}
try catch in java

Try & Catch Block:

When try and catch keywords come in pair

Syntax:

try{
    // Block of code

Catch{
    // Block of code
}

Example:

Run
import java.util.*;

public class Main{  
    public static void main(String[] args) {  
        // try block 
		try  {
			// try block statements
            System.out.println("I am in Try Block");
            int data=50/0;    
        }
		// catch block
        catch(ArithmeticException e){
			// catch block exceptions
            System.out.println(e); 
            System.out.println("Catch Block Executed"); 
        }
    }    
}
Output:

I am in Try Block
java.lang.ArithmeticException: / by zero
Catch Block Executed

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription