Java is one of the most popular programming languages that are used in web development. Like all languages, even programming languages have certain nuances that need to be understood.

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs during the execution of program (application), the normal flow of the program is disrupted, and the program/Application terminates abnormally whereby the whole coding may corrupt (if there was no backup). Therefore, these exceptions must be handled for a smooth run.

In Java, the catch block is used to handle exceptions that occur in a try block. It provides a mechanism to gracefully manage errors and prevent program termination. Understanding catch blocks is essential for robust error handling in Java applications. Enroll in a Java Course to master exception handling and enhance your programming proficiency.

According to Oracle, there are three categories of exceptions:

1. Checked Exception

The classes which directly inherit Throwable class with the exclusion of Runtime Exception and Error are known as checked exceptions. IO Exceptions, SQL Exceptions etc. are some of the known examples of checked exceptions. The Checked exceptions are checked at compile-time.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

2. Unchecked Exception

The classes which inherit Runtime Exception are known as unchecked exceptions e.g. of unchecked exceptions include Arithmetic Exception, Null Pointer Exception, Array Index Out Of Bounds Exception etc. Unlike checked exceptions, they are not checked at compile-time rather the unchecked exceptions are checked at runtime.

3. Error

Error is irrecoverable. There are two main types of errors:

1. A Runtime error is called an Exceptions It is any event (or exception) that interrupts the normal flow of program execution.

2. The Compile time error is the second category of error which is further sub-divided into two types:

  • Syntax Errors-A syntax error occur when there is some sort of mistake in the language usage, for e.g. a missing comma or parenthesis or in a statement where a condition is parenthesis while it’s not defined. The compiler and run-time can detect these errors.
  • Semantic Errors- A semantic error occurs when the syntax is correct but the code usage is incorrect. For e.g. a code usage in which the variable is isn’t initialized correctly. The Compiler can detect the semantic errors.

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Why We Need an Exception?

The Exception handling of Try catch in Java ensures that the flow of the program doesn’t break when the exception occurs during the running of program. For example, if there is a program that has a bunch of statements and an exception occurs mid way after executing certain statements of the application (program) then the statements after the exception will not execute and the program will terminate abruptly by handling the exception we make sure that all the statements execute and the flow of program doesn’t break during its runtime.

The Try Block of Try Catch in Java

A try block is the block of code (contains a set of statements) in which exceptions can occur; it's used to enclose the code that might throw an exception. The try block is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be used within the method and it must be followed by a catch block(s) or finally block or both.

Syntax of Try block

  1. try{    
  2. //code that may throw an exception    
  3. }catch(Exception) {
  4. //code
  5. }    

So if you think while writing a program that certain statements in the program can throw an exception or series of exception, enclosed them in try block and handle that exception smoothly without hampering the program.

The Catch Block of Try Catch in Java

The catch block catches and handles the try block exceptions by declaring the type of exception within the parameter. The catch block includes the code and it is executed if an exception inside the try block occurs. The catch block is where you handle the exceptions; so this block must be follow the try block.

The declared exception in catch block must be the parent class exception ( i.e., Exception) or the generated exception type. However, the best approach is to declare the generated type of exception.

In the Java language, you can use a try block without a catch block but you can’t use the catch block without a try block.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Multiple Catch Blocks

A single try block can have one or several catch blocks associated with it. You can catch different exceptions in different catch blocks if it contains a different exception handler. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. So, if you have to perform different tasks at the occurrence of different exceptions, you can use the multi-try catch in Java.

Example- creating an integer array named ‘arr’ of the size 10

class ListOfNumbers {

  public int[] arr = new int[10];

  public void writeList() {

try {

   arr[10] = 11;

}

catch (NumberFormatException e1) {

      System.out.println("NumberFormatException => " + e1.getMessage());

}

catch (IndexOutOfBoundsException e2) {

      System.out.println("IndexOutOfBoundsException => " + e2.getMessage());

}

  }

}

class Main {

  public static void main(String[] args) {

ListOfNumbers list = new ListOfNumbers();

list.writeList();

  }

}

Output

Have a look at arr[10] = 11 in the program; Since we are trying to assign a value to the index 10 (array index starts from 0 and ends at arr[9]).Henceforth Index Out Of Bound Exception error occurs. The first catch block does not handle the Index Out Of Bounds Exception (Error), so it is passed to the next catch block. The second catch block in the aforementioned example has the correct exception handler because it handles an Index Out Of Bounds Exception. Hence, the said program is executed.

When executing a Java code, different types of errors or exceptions can occur thereby making the program stop and generating an error message or technically putting the Java throws an exception(s). It could be due to the coding errors, errors due to wrong input, or other unforeseeable things. The Try Catch in java statements allows you to define a block of code to be tested for exceptions (errors) while it is being executed. The Try Catch in Java always occurs in pairs; the catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Master Full Stack Development With Simplilearn

If you wish to master java and become a full stack pro within 6 months, you must enroll in Simplilearn’s Java Certification Training. This  Program is an intense bootcamp, in partnership with Caltech and IBM, that will help you become a successful java professional. Start your learning journey today.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449