Java try-catch block

Last updated on Dec 27 2022
Prabhas Ramanathan

Table of Contents

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

1. try{ 
2. //code that may throw an exception 
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{ 
2. //code that may throw an exception 
3. }finally{}

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try block.

Problem without exception handling

Let’s try to understand the problem if we don’t use a try-catch block.

Example 1

1. public class TryCatchExample1 { 
2. 
3. public static void main(String[] args) { 
4. 
5. int data=50/0; //may throw exception 
6. 
7. System.out.println("rest of the code"); 
8. 
9. } 
10. 
11. }

Output:

Exception in thread “main” java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling

 

Let’s see the solution of the above problem by a java try-catch block.

Example 2

1. public class TryCatchExample2 { 
2. 
3. public static void main(String[] args) { 
4. try 
5. { 
6. int data=50/0; //may throw exception 
7. } 
8. //handling the exception 
9. catch(ArithmeticException e) 
10. { 
11. System.out.println(e); 
12. } 
13. System.out.println("rest of the code"); 
14. } 
15. 
16. }

 

Output:
java.lang.ArithmeticException: / by zero

rest of the code
Now, as displayed in the above example, the rest of the code is executed, i.e., the rest of the code statement is printed.

Example 3

In this example, we also kept the code in a try block that will not throw an exception.

1. public class TryCatchExample3 { 
2. 
3. public static void main(String[] args) { 
4. try 
5. { 
6. int data=50/0; //may throw exception 
7. // if exception occurs, the remaining statement will not exceute 
8. System.out.println("rest of the code"); 
9. } 
10. // handling the exception 
11. catch(ArithmeticException e) 
12. { 
13. System.out.println(e); 
14. } 
15. 
16. } 
17. 
18. }

 

Output:
java.lang.ArithmeticException: / by zero

Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.

Example 4

Here, we handle the exception using the parent class exception.

1. public class TryCatchExample4 { 
2. 
3. public static void main(String[] args) { 
4. try 
5. { 
6. int data=50/0; //may throw exception 
7. } 
8. // handling the exception by using Exception class 
9. catch(Exception e) 
10. { 
11. System.out.println(e); 
12. } 
13. System.out.println("rest of the code"); 
14. } 
15. 
16. }

 

Output:
java.lang.ArithmeticException: / by zero

rest of the code

Example 5

Let’s see an example to print a custom message on exception.

1. public class TryCatchExample5 { 
2. 
3. public static void main(String[] args) { 
4. try 
5. { 
6. int data=50/0; //may throw exception 
7. } 
8. // handling the exception 
9. catch(Exception e) 
10. { 
11. // displaying the custom message 
12. System.out.println("Can't divided by zero"); 
13. } 
14. } 
15. 
16. }

Output:
Can’t divided by zero

Example 6

Let’s see an example to resolve the exception in a catch block.

1. public class TryCatchExample6 { 
2. 
3. public static void main(String[] args) { 
4. int i=50; 
5. int j=0; 
6. int data; 
7. try 
8. { 
9. data=i/j; //may throw exception 
10. } 
11. // handling the exception 
12. catch(Exception e) 
13. { 
14. // resolving the exception in catch block 
15. System.out.println(i/(j+2)); 
16. } 
17. } 
18. }

 

Output:
25

Example 7

In this example, along with try block, we also enclose exception code in a catch block.

1. public class TryCatchExample7 { 
2. 
3. public static void main(String[] args) { 
4. 
5. try 
6. { 
7. int data1=50/0; //may throw exception 
8. 
9. } 
10. // handling the exception 
11. catch(Exception e) 
12. { 
13. // generating the exception in catch block 
14. int data2=50/0; //may throw exception 
15. 
16. } 
17. System.out.println("rest of the code"); 
18. } 
19. }

 

Output:

Exception in thread “main” java.lang.ArithmeticException: / by zero

Here, we can see that the catch block didn’t contain the exception code. So, enclose exception code within a try block and use catch block only to handle the exceptions.

 

Example 8

In this example, we handle the generated exception (Arithmetic Exception) with a different type of exception class (ArrayIndexOutOfBoundsException).

1. public class TryCatchExample8 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7.
8. }
9. // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }

 

Output:
Exception in thread “main” java.lang.ArithmeticException: / by zero

Example 9

Let’s see an example to handle another unchecked exception.

1. public class TryCatchExample9 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int arr[]= {1,3,5,7};
7. System.out.println(arr[10]); //may throw exception
8. }
9. // handling the array exception
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }

 

Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code

Example 10

Let’s see an example to handle checked exception.

1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }

 

Output:
File saved successfully

Internal working of java try-catch block

java 88

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.

Java catch multiple exceptions

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember

• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.

Example 1

Let’s see a simple example of java multi-catch block.

1. public class MultipleCatchBlock1 { 
2. 
3. public static void main(String[] args) { 
4. 
5. try{ 
6. int a[]=new int[5]; 
7. a[5]=30/0; 
8. } 
9. catch(ArithmeticException e) 
10. { 
11. System.out.println("Arithmetic Exception occurs"); 
12. } 
13. catch(ArrayIndexOutOfBoundsException e) 
14. { 
15. System.out.println("ArrayIndexOutOfBounds Exception occurs"); 
16. } 
17. catch(Exception e) 
18. { 
19. System.out.println("Parent Exception occurs"); 
20. } 
21. System.out.println("rest of the code"); 
22. } 
23. }

 

Output:
Arithmetic Exception occurs
rest of the code

Example 2

1. public class MultipleCatchBlock2 { 
2. 
3. public static void main(String[] args) { 
4. 
5. try{ 
6. int a[]=new int[5]; 
7. 
8. System.out.println(a[10]); 
9. } 
10. catch(ArithmeticException e) 
11. { 
12. System.out.println("Arithmetic Exception occurs"); 
13. } 
14. catch(ArrayIndexOutOfBoundsException e) 
15. { 
16. System.out.println("ArrayIndexOutOfBounds Exception occurs"); 
17. } 
18. catch(Exception e) 
19. { 
20. System.out.println("Parent Exception occurs"); 
21. } 
22. System.out.println("rest of the code"); 
23. } 
24. }

 

Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code

Example 3

In this example, try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is invoked.

1. public class MultipleCatchBlock3 { 
2. 
3. public static void main(String[] args) { 
4. 
5. try{ 
6. int a[]=new int[5]; 
7. a[5]=30/0; 
8. System.out.println(a[10]); 
9. } 
10. catch(ArithmeticException e) 
11. { 
12. System.out.println("Arithmetic Exception occurs"); 
13. } 
14. catch(ArrayIndexOutOfBoundsException e) 
15. { 
16. System.out.println("ArrayIndexOutOfBounds Exception occurs"); 
17. } 
18. catch(Exception e) 
19. { 
20. System.out.println("Parent Exception occurs"); 
21. } 
22. System.out.println("rest of the code"); 
23. } 
24. }

 

Output:
Arithmetic Exception occurs
rest of the code

Example 4

In this example, we generate NullPointerException, but didn’t provide the corresponding exception type. In such case, the catch block containing the parent exception class Exception will invoked.

1. public class MultipleCatchBlock4 { 
2. 
3. public static void main(String[] args) { 
4. 
5. try{ 
6. String s=null; 
7. System.out.println(s.length()); 
8. } 
9. catch(ArithmeticException e) 
10. { 
11. System.out.println("Arithmetic Exception occurs"); 
12. } 
13. catch(ArrayIndexOutOfBoundsException e) 
14. { 
15. System.out.println("ArrayIndexOutOfBounds Exception occurs"); 
16. } 
17. catch(Exception e) 
18. { 
19. System.out.println("Parent Exception occurs"); 
20. } 
21. System.out.println("rest of the code"); 
22. } 
23. }

 

Output:
Parent Exception occurs
rest of the code

Example 5

Let’s see an example, to handle the exception without maintaining the order of exceptions (i.e. from most specific to most general).

1. class MultipleCatchBlock5{ 
2. public static void main(String args[]){ 
3. try{ 
4. int a[]=new int[5]; 
5. a[5]=30/0; 
6. } 
7. catch(Exception e){System.out.println("common task completed");} 
8. catch(ArithmeticException e){System.out.println("task1 is completed");} 
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} 
10. System.out.println("rest of the code..."); 
11. } 
12. }

 

Output:
Compile-time error
The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

1. ….
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ….

Java nested try example

Let’s see a simple example of java nested try block.

1. class Excep6{ 
2. public static void main(String args[]){ 
3. try{ 
4. try{ 
5. System.out.println("going to divide"); 
6. int b =39/0; 
7. }catch(ArithmeticException e){System.out.println(e);} 
8. 
9. try{ 
10. int a[]=new int[5]; 
11. a[5]=4; 
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} 
13. 
14. System.out.println("other statement); 
15. }catch(Exception e){System.out.println("handeled");} 
16. 
17. System.out.println("normal flow.."); 
18. } 
19. }

Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.

java 89

Note: If you don’t handle exception, before terminating the program, JVM executes finally block(if any).

Why use java finally

• Finally block in java can be used to put “cleanup” code such as closing a file, closing connection etc.

Usage of Java finally

Let’s see the different cases where java finally block can be used.
Case 1
Let’s see the java finally example where exception doesn’t occur.

1. class TestFinallyBlock{ 
2. public static void main(String args[]){ 
3. try{ 
4. int data=25/5; 
5. System.out.println(data); 
6. } 
7. catch(NullPointerException e){System.out.println(e);} 
8. finally{System.out.println("finally block is always executed");} 
9. System.out.println("rest of the code..."); 
10. } 
11. }

 

Output:5
finally block is always executed
rest of the code…

Case 2

Let’s see the java finally example where exception occurs and not handled.

1. class TestFinallyBlock1{ 
2. public static void main(String args[]){ 
3. try{ 
4. int data=25/0; 
5. System.out.println(data); 
6. } 
7. catch(NullPointerException e){System.out.println(e);} 
8. finally{System.out.println("finally block is always executed");} 
9. System.out.println("rest of the code..."); 
10. } 
11. }

 

Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

Case 3

Let’s see the java finally example where exception occurs and handled.

1. public class TestFinallyBlock2{ 
2. public static void main(String args[]){ 
3. try{ 
4. int data=25/0; 
5. System.out.println(data); 
6. } 
7. catch(ArithmeticException e){System.out.println(e);} 
8. finally{System.out.println("finally block is always executed");} 
9. System.out.println("rest of the code..."); 
10. } 
11. }

 

Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code…

Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

So, this brings us to the end of blog. This Tecklearn ‘Java try-catch block’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread
File Handling in Java
• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Java try-catch block"

Leave a Message

Your email address will not be published. Required fields are marked *