Upskill faster and boost your growth in 2024 with our upto 50% OFF on All Courses! Offer Ending in
D
H
M
S
Get Now
Exception handling in Java: Try, Catch, Finally, Throw and Throws

Exception handling in Java: Try, Catch, Finally, Throw and Throws

22 Sep 2023
Intermediate
1.03K Views
9 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming Course

Start Learning Free View All Courses

Exception Handling in Java: An Overview

Exception handling in Java is an unwanted event that happens during the execution of the program. To Learn Java and how to handle exceptions in Java can be answered by terminating the program by affecting the flow of the program.

What is Exception Handling in Java?

Exception handling in Java is an unwanted event that happens during the execution of the program. How to handle an exception in Java can be answered by using jump statements in Java, which involve terminating the program or affecting the flow of the program.

 There are various reasons that cause exception handling in Java, such as:

  • Device failure
  • Loss of network connection
  • Invalid user input
  • Code errors
  • Opening an unavailable file
  • Physical limitations

Types of Exceptions in Java

There are two types of exception handling in Java, which are

  1. Unchecked or Runtime Exceptions in Java
  2. Checked or Compile-time Exceptions in Java
  3. Errors

Runtime Exception or unchecked exception in Java

Runtime Exception or unchecked exception in Java happens because of the error in coding involving Strings in Java. This is also called an unchecked exception because it is not checked at compile time, but it is checked at Runtime.

 Some Runtime Exception is,

  • Null pointer
  • Out-of-bounds array access
  • Dividing a number by 0
  • Improper use of an API

Compile Time Exceptions or checked exceptions in Java

Compile time exceptions are handled by the compiler so that it is called a checked exception. There are some examples of checked exceptions, those are

  • Read past the end of a file
  • Open a file that does not exist

Errors in java

  • Java errors are essential for identifying problems with program execution.
  • They are essential to debugging since they help developers find and fix issues.
  • Error exceptions are specific and provide problem descriptions, which makes it easier to identify errors.
  • Error exceptions give developers an organized way to handle problems, preventing them from having to start over.
  • The "catch" keyword allows for the quick detection of errors and subsequent corrective action.
  • Error exceptions can have a number of causes, including memory leaks, problems with input validation, and server troubles.
  • Java errors assist in real-time debugging during software development, regardless of the reason.
  • They help in the early identification of potential problems before the deployment of programs by preventing catastrophic errors during testing.

Exception Hierarchy in Java

Exception hierarchy in Java can be defined by this picture:

How to handle exceptions in java?

In Java, there are different ways to approaches to exception handling those are

  • Try..catch the block
  • Finally, block
  • Throw and throw keywords

Try..catch block in Java

Try.. catch block is generally used in Java for doing exception handling. Here, in Java, a code might generate an exception in the "try" block. All the "try" blocks here are followed by "catch" blocks for catching the exception.

Syntax

try
  {
    // code
  }
  catch(Exception e)
  {
    // code
  }

Example

class Main
{
    public static void main(String[] args)
    {
      try
      {
        // code that generate exception
        int divideByZero = 5 / 0;
        System.out.println("Rest of code in try block");
      }
      catch (ArithmeticException e) {
        System.out.println("ArithmeticException => " + e.getMessage());
      }
    }
  }

This Java example shows how to handle exceptions. It tries to divide by zero, which results in an ArithmeticException that is handled in the catch block and outputs an error.

Output

ArithmeticException => / by zero

Finally block in Java

Finally block in Java always executes even if there are no exceptions. This is an optional block. For every try block there could be one final block. This Finally block executes after try..catch block.

Syntax

try
  {
    //code
  }
  catch (ExceptionType1 e1)
  {
    // catch block
  }
  finally
  {
    // finally block always executes
  }

Example

class Main
 {
    public static void main(String[] args)
    {
      try
      {
        // code that generates exception
        int divideByZero = 5 / 0;
      }
      catch (ArithmeticException e)
      {
        System.out.println("ArithmeticException => " + e.getMessage());
      }
      finally
      {
        System.out.println("This is the finally block");
      }
    }
  }

In this Java example, trying to divide by zero results in an ArithmeticException that is caught and accompanied by an error message. The "finally" block also always runs, printing "This is the finally block" whether or not an exception was raised.

Output

ArithmeticException => / by zero

Throw and throw keywords in Java

The throw keyword in Java is used for explicitly throwing a single exception. When an exception is ready to throw then the program moves to try block to catch the block

Example

class Main
{
    public static void divideByZero()
    {
      // throw an exception
      throw new ArithmeticException("Trying to divide by 0");
    }
    public static void main(String[] args)
    {
      divideByZero();
    }
  }

This Java example develops a method 'divideByZero()' that is invoked in the main method and purposefully raises an ArithmeticException with a customized message. It raises the exception with the provided message when it is run.

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
        at Main.divideByZero(Main.java:5)
        at Main.main(Main.java:9)

FAQs

1. What is exception handling in Java?

In order to avoid crashes and allow for regulated error recovery, Java's exception-handling procedure deals with unforeseen or extraordinary occurrences that occur during program execution.

2. What are the 5 keywords in Java exception handling?

Try, Catch, Throw, Throws, and Finally are the five keywords used in Java exception handling.

3. What are the types of exceptions in Java?

Checked (compile-time checked) and unchecked (runtime) exceptions are the two categories used to classify Java exceptions.

4. What type of error is an exception?

In Java, an exception is a technique for dealing with extraordinary runtime circumstances and is not regarded as a mistake.

5. What is a catch block in Java?

Specific Java exceptions are captured and handled in a catch block, enabling a controlled response to unusual events that take place inside a try block.

Summary

This article covers exception handling in Java, including how to handle exception handling in Java. It also includes the various types of exception handling in Java with examples. If you're looking to learn Java, this article will provide you with insights into effectively managing exceptions in your code. Through this detailed exploration of exception handling in Java, learners undergoing Java Certification training can develop a solid understanding of this crucial topic and acquire the necessary skills to effectively handle exceptions in their Java programs.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this