Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Try Block
2.1.
Syntax of Try Block
3.
What is a Catch Block?
3.1.
Syntax of a catch block
4.
Internal working of Java try-catch block
4.1.
Example
4.1.1.
Code1
4.1.2.
Code2
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Try catch block

Author Mohammad Saalim
2 upvotes
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

The try-catch block contains a set of statements where an exception occurs. A catch block always comes after a try block, which handles the exception inside a try block. 

Must Read, Multithreading in Java  and Also read, Duck Number in Java

 

Try Block

A block of code encloses the code, which might give an exception. It should be defined within a function. 

If an exception has occurred at the particular statement in the try block, the rest of the block code will not execute. A try block must be followed by either catch block, finally block, or both. 

Syntax of Try Block

try {
	// a set of statements that may cause an exception.
}


Also see,  Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is a Catch Block?

A catch block is a block where you handle the exceptions. It handles the exception by declaring the type of exception within the parameter. You can catch different exceptions in different catch blocks. You can use multiple catch blocks with a single try block.

Syntax of a catch block

try {
	// statement might cause an exception
}
catch(exception(type) e (object))
{
	//error handling code
}

Internal working of Java try-catch block

The JVM firstly checks whether the exception can be handled or not. If it cannot be dealt with, JVM gives a default exception handler that performs the following tasks:

  • It prints out the exception description.
  • It prints the stack trace (Hierarchy of methods where the exception occurred).
  • It causes the code to terminate.

Example

Code1

public class Ex {
	public static void main(String[] args) {
		int data = 10/0; // it will throw an exception.
		System.out.println("rest of the code");
	}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at CODING/CN.Ex.main(Ex.java:7)


In this example, we simply divide the number by zero. In the output section, we have received an exception message in output section that this number cannot be divided by zero.

Try it on online java compiler.

Code2

public class Ex8 {
	public static void main(String[] args){
		try
		{
    		int data = 100/0; // may throw an exception
		}
		//handling exception
		catch(ArithmeticException e)
		{
  			System.out.println(e);
    	}
    	System.out.println("rest of the code");
    }
}

Output:

java.lang.ArithmeticException: / by zero
rest of the code


In this code, the section we applied some arithmetic to divide the number by zero. In this section, we have used the try-catch block statement. In the try block, we received some arithmetic operation and was the send further block to an exception to catch it. This will help you to execute the further part of the code as it is. 

Must Read Static Blocks In Java and Hashcode Method in Java

Frequently Asked Questions

  1. What are the advantages of Java to try to catch block statement?
    The use of try/catch block is used to differentiate between the code showing the error and showing the correct output, thereby maintaining the logical flow of the program. 
     
  2. Can we handle errors in a catch block?
    Yes, we can, with the help of the throwable class, which is the superclass of all the exceptions in the Java language. Java Virtual Machine throws only the objects that are instances of this class.

Key Takeaways

We have covered the following topics regarding try-catch block in this blog.

A brief introduction about try catch block and also what is try block and what is catch block along with its syntax of both cases. Internal working of java try-catch block with a few examples of try catch block statements.  

If you want to learn more about Java and Resources to learn Java, you can visit our website, Learn Java Programming.

Previous article
Throws keyword
Next article
Java lang ExceptionInInitializerError
Live masterclass