Java Exception – Types & Java Catch Exceptions

1. Java Exception – Objective

In our last tutorial, we studied Java Comments. Here, in this Java tutorial, we are going to learn Java Exception. We will also discuss Java Exception List: Java Errors, Checked and unchecked exceptions in Java and Exception Hierarchy in Java. Moreover, we will study Java Catch Exception: Multiple Catch Blocks, Throws/Throw Keywords, The Finally Block, and try-with-resources in Java with some Java Exception Example to understand it better.

So, let’s start the Java Exception list.

Java Exception

Java Exception – Types & Java Catch Exceptions

2. What is Java Exception?

Java exception (or remarkable occasion) is an issue that emerges amid the execution of a program. At the point when an Exception in Java happens the typical stream of the program is disturbed and the program/Application ends unusually, which isn’t suggested, in this way, these special cases are to dealt with.

Let’s study Exception Handling in Java With examples

Java exception can happen for some, extraordinary reasons. Following are a few situations where an exemption happens.

  • A user has entered an invalid information.
  • A document that should open can’t found.
  • The system association has been lost amidst interchanges or the JVM has come up short in memory.

Some of these Java exceptions are caused by user’s mistake, others by developer blunder, and others by physical assets that have flopped in some way.

3. Categories of Java Exception

We have three types of Java Exceptions. You have to comprehend them to know how special case taking care of functions in Java.

Let’s learn about Java Class and Object to Learn OOPs in Java

Java Exception Tutorial - Types of Exception in Java

Java Exception Tutorial – Types of Exception in Java

The Java Exception List –

a. Checked Exception in Java

Java checked exception is a special case that happens at the incorporate time, these are additionally called as assembling time exemptions. These special cases can’t just disregard at the season of assemblage, the software engineer should deal with (handle) these exemptions.

Let’s Explore Java Character Class Methods with Syntax and Examples

For instance, on the off chance that you utilize FileReader class in your program to peruse information from a record, if the document determined in its constructor doesn’t exist, at that point a FileNotFoundException happens, and the compiler prompts the developer to deal with the special case.

Example –

import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo
   {
       public static void main(String args[])
          {                 
              File file = new File("E://file.txt");
              FileReader fr = new FileReader(file);
          }
  }

b. Unchecked Exception in Java

Java Unchecked Exception is a special exemption that happens at the season of execution. These are additionally called as Runtime Exception in Java. These incorporate programming bugs, for example, rationale blunders or dishonorable utilization of an API. Runtime special cases are overlooked at the season of gathering.

Do You Know How Java Inheritance is used

For instance, in the event that you have proclaimed a variety of size 5 in your program, and endeavoring to call the sixth component of the cluster then an ArrayIndexOutOfBoundsExceptionexception happens.

Example –

public class Unchecked_Demo
{  
   public static void main(String args[])
{
      int num[] = {1, 2, 3, 4};
      System.out.println(num[5]);
   }
}

c. Java Error

Java Error is not an exception by any means, but rather issues that emerge outside the ability to control the user or the developer. Errors in Java are normally overlooked in your code since you can seldom take care of a mistake. For instance, if a stack flood happens, a blunder will emerge. They are additionally overlooked at the season of aggregation.

Read about Polymorphism in Java with Example

4. Exception Hierarchy in Java

All Java exception classes are subtypes of the java.lang.Exception class. The special case class is a subclass of the Throwable class. Other than the special case class we also have another subclass called Error which we get from the Throwable class.

Java Errors are irregular conditions that occur if there should an occurrence of extreme disappointments, these are not taken care of by the Java programs. Errors are created to demonstrate blunders produced by the runtime condition. Case: JVM is out of memory. Ordinarily, programs can’t recuperate from blunders.

Let’s Look at Difference between Abstraction & Encapsulation in Java

Java Exception class has two primary subclasses: IOException class and RuntimeException Class.

Java Exception - Exception Hierarchy in Java

Java Exception – Exception Hierarchy in Java

a. Java Exception Methods

These are the following methods used in Java Exception:

  • Public String getMessage() – This method returns the detailed of the exception.
  • Public Throwable getCause() – This method the cause of an exception.
  • Public String toString() – This method returns the class concatenated.
  • Public void printStackTrace() – This method returns the result along with the stack trace.
  • Public StackTraceElement [] getStackTrace() – This returns an array containing each element. 0 is the index starting of call stack.
  • Public Throwable fillInStackTrace() – This method fills the stalk trace of throwable objects.

Read about Serialization and Deserialization in Java

Java Quiz

5. Java Catching Exceptions

A method gets a special case utilizing a mix of the try and catch catchphrases. A try/catch square is put around the code that may produce an exemption. Code inside an catch/try piece allud to as ensure code.

Syntax –

try
  {
// Protected code
  }
catch (ExceptionName e1)
  {
// Catch block
  }
Java Exception Tutorial - Java Catch Exception

Java Exception Tutorial – Java Catch Exception

At the point when a special case happens, that exemption happen is dealt with by getting piece relate to it. A catch explanation includes announcing the kind of special case you are attempting to get. In the event that an exemption happens in the ensured code, the catch square (or hinders) that takes after the attempt check. On the off chance that the kind of exemption that happens record in a catch obstruct, the special case pass to the catch square much as a contention pass into a technique parameter.

Let’s Learn Linear Data Structures in Java

Example –

import java.io.*;
public class ExcepTest
   {
      public static void main(String args[])
       {
          try
           {
              int a[] = new int[2];
              System.out.println("Access element three :" + a[3]);
           }
      catch (ArrayIndexOutOfBoundsException e)
         {
            System.out.println("Exception thrown  :" + e);
         }
    System.out.println("Out of the block");
     }
  }

a. Multiple Catch Blocks in Java

There can multiple catch block in Java too.

Syntax –

try
  {
// Protected code
  }
catch (ExceptionType1 e1)
  {
// Catch block
  }
catch (ExceptionType2 e2)
  {
// Catch block
  }
catch (ExceptionType3 e3)
  {
// Catch block
  }

The past explanations show three catch pieces, yet you can have any number of them after a single attempt. On the off chance that an exemption happens in the ensure code, the special case toss to the principal gets hinder in the rundown. Occasionally the information sort of the special case tossed matches ExceptionType1, it gets capture there. If not, the special case goes down to the second catch articulation.

Read about Java Abstract Data Type in Data Structure

Example –

try
 {
    file = new FileInputStream(fileName);
    x = (byte) file.read();
  }
catch (IOException i)
  {
    i.printStackTrace();
    return -1;
 }
catch (FileNotFoundException f) // Not valid!
 {
    f.printStackTrace();
    return -1;
 }

b. The Throws/Throw Keywords in Java

Occasionally, a method does not deal with a checked exception, the method must pronounce it utilizing the throws keyword. The throws keyword shows up toward the finish of a strategy’s mark.

You can toss an exception, either a recently instantiated one or an exemption that you just got, by utilizing the throw watchword.

Example –

import java.io.*;
public class className
  {
   public void deposit(double amount) throws RemoteException
     {
// Method implementation
        throw new RemoteException();
      }
// Remainder of class definition
  }

Multiple throws can also happen in a method.

Do You Know About Java Comparator Interface – Working of CollectionsSort()

Example –

import java.io.*;
public class className
  {
     public void withdraw(double amount) throws RemoteException,
      InsufficientFundsException
    {
// Method implementation
    }
// Remainder of class definition
 }

c. The Finally Block in Java

The finally block takes after try or a catch block. An at long last piece of code dependably executes, regardless of an event of an Exception.
Utilizing an at finally block enables you to run any cleanup-type explanations that you need to execute, regardless of what occurs in the ensured code.

Syntax –

try
{
   // Protected code
}
catch (ExceptionType1 e1)
{
   // Catch block
}
catch (ExceptionType2 e2)
{
   // Catch block
}
catch (ExceptionType3 e3)
{
   // Catch block
}
finally
{
   // The finally block always executes.
}

Example –

public class ExcepTest
 {
    public static void main(String args[])
     {
        int a[] = new int[2];
        try
         {
            System.out.println("Access element three :" + a[3]);
          }
        catch (ArrayIndexOutOfBoundsException e)
           {
              System.out.println("Exception thrown  :" + e);
           }
        finally
           {
              a[0] = 6;
              System.out.println("First element value: " + a[0]);
              System.out.println("The finally statement is executed");
           }
      }
  }

Note –

A try statement cannot work without catch clause or a finally clause and a catch clause without try statement.

It is not mandatory to have a finally clause.

No other code can present between the three clauses.

Read Also, the Island of Isolation in Java with Example

d. The try-with-resources in Java

For the most part, when we utilize any resources like streams, associations, and so on we need to close them expressly utilizing at long finally block. In the program below, we are perusing information from a record utilizing FileReader and we are shutting it utilizing at finally block.

Example –

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadData_Demo
   {
      public static void main(String args[])
       {
         FileReader fr = null;                  
         try
           {
              File file = new File("file.txt");
              fr = new FileReader(file); char [] a = new char[50];
              fr.read(a);
// reads the content to the array
              for(char c : a)
              System.out.print(c);  
// prints the characters one by one
           }
      catch (IOException e)
           {
             e.printStackTrace();
           }
      finally
          {
             try
              {
                 fr.close();
              }
            catch (IOException ex)
             {                   
                ex.printStackTrace();
             }
         }
     }
 }

They are also refer to automatic resource management.

To utilize this announcement, you just need to pronounce the required assets inside the bracket, and the made asset will shut consequently toward the finish of the piece. Following is the sentence structure of try-with-resources proclamation.

What is Multithreading in Java 

Following focuses are to remember while working with try-with-resources articulation.

While you announce different classes in the try square of try-with-resources explanation these classes are shut backward request.

But the revelation of assets inside the bracket everything is the same as would expect try/catch square of a try piece.

The asset announces in try gets instantiate just before the beginning of the try-block.

The asset pronounces at the try block is certainly proclaim as last.

So, this was all about Java Exception Tutorial. Hope you like our explanation.

6. Conclusion

Hence, in this Java Exception tutorial, we learned about Java Exception List: Java Errors, Checked & unchecked exceptions in Java. Moreover, we studied Java exception example and Exception Hierarchy in Java. At last, we saw Java Catch Exception: Multiple Catch Blocks, Throws/Throw Keywords, Finally Block, and try-with-resources in Java. Furthermore, if you have any query feel free to ask in the comment section.

Related Topic- Switch Statement in Java 

For reference

No Responses

  1. shagufta says:

    Can we use “throws FileNotFoundException” and try-catch() in the same program?

Leave a Reply

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