logo

Java Exceptions


Show

An exception is a crisis that occurs throughout the execution of a list. When an Exception crop ups the usual flow of the plan is interrupted and the program/Application ends abnormally, which is not advised, consequently, these exceptions are to be managed.

An exception can take place for numerous dissimilar reasons. Subsequent are several scenarios where an exception arises.

  • A user has pierced unsound data.
  • A file that requires to be unlocked never be found.
  • A network association has been mislaid in the focus of statements or the JVM has run out of memory.

A few of these exceptions are reasoned by user fault, others by programmer fault, and others by corporeal resources that have not passed in several manners.

Anchored in these, we encompass three categories of Exceptions. You require understanding them to recognize how omission conduct works in Java.

  • Checked exceptions − An ensured exemption is an exception that is verified (notified) by the compiler. Therefore, at compilation-time, these methods are also called amass time exceptions. These immunities never simply are disregard, the programmer should mind of (manage) these exceptions.

For case, if you employ FileReader class in your program to interpret data from a file if the file particular in its constructor does not exist, then a FileNotFoundException occurs, and the compiler punctual the programmer to knob the exception.

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); 
   }
}

If you try to compile the above program, you will get the following exceptions.

Output

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
      FileReader fr = new FileReader(file);
                      ^
1 error

Note − as the techniques read() and close() of FileReader class flings IOException, you can watch that the compiler notify to knob IOException, along with FileNotFoundException.

  • Unchecked exceptions − An unchecked exemption is an exception that comes about on the occasion of execution. These are too called Runtime Exceptions. These incorporate programming bugs, such as reason errors or rude use of an API. Runtime exceptions are disregard at the time of collection.

For instance, if you have stated a selection of size 5 in your plan, and annoying to call the 6th constituent of the collection then an ArrayIndexOutOfBoundsExceptionexception occurs.

Example

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

If you compile and execute the above program, you will get the following exception.

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Errors − these are no exemptions at every, but troubles that arise outside the run of the client or the programmer. Faults are characteristically disregarded in your system because you can hardly ever do something concerning a slip. For instance, if a pile excess happens, an inaccuracy will occur. They also disregard it at the time of collection.

Exception Hierarchy

All exemption groups are subtypes of the java.lang.Exception class. The exemption class is a subclass of the Throwable class. Except for the exception, class there is one more subclass called Error, which is derived from the Throwable class.

Blunders are irregular states that occur in case of harsh failures, these are not managed by the Java programs. Errors are produced to designate errors produced by the runtime environment. Instance: JVM is out of memory. usually, programs cannot get well from faults.

Exceptions

Following is a list of the most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods

Following is the list of important methods available in the Throwable class.

Sr.No.Method & Description
1

public String getMessage()

Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

2

public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

3

public String toString()

Returns the name of the class concatenated with the result of getMessage().

4

public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output stream.

5

public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

6

public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Catching Exceptions

A process catches an exemption with an amalgamation of the try and grabs keywords. A try/catch block is put around the system that power generates an exemption. The system within an attempt/grasp block is submitted to as defended code, and the syntax for with try/catch seems like the following

Syntax

try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}

The code, which is prone to exceptions, rests in the endeavor block. When an exemption happens, that exemption occurred is managed by catch block associated with it. Every try hunk should either be without delay or by a catch block or lastly block.

A grasp statement engages declaring the kind of exemption you are annoying to grab. If an exception happens in a protected system, the catch block (or blocks) that follow the endeavor is checked. If the category of exemption that occurred is inventoried in a grasping block, the exemption is passed to the grasp block much as a quarrel is a bypass into a technique parameter.

Example

The subsequent is a collection declared with 2 constituents. Then the code tries to admission the 3rd part of the array, which throws an exemption.

// File Name : ExcepTest.java
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");
   }
}

This will produce the following result:

Output

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −

Syntax

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

The preceding statements reveal three grasp blocks, except you could have any digit of them following a single try. If an exemption occurs in the kept code, the exemption is terrified to the first grab block in the record. If the data kind of the immunity terrified matches ExceptionType1, it gets fixed there. If not, the exclusion passes downhill to the second catch statement. This persists either the exception is fixed or falls through entire catches, in which case the present method ends execution or the exception is unnerved down to the preceding method on the call stack.

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;
}

Catching Multiple Type of Exceptions

Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it:

catch (IOException'FileNotFoundException ex) {
   logger.log(ex);
   throw ex;

The Throws/Throw Keywords

If a technique does not knob a checked exemption, the method must state it utilizing the throws keyword. The toss keyword emerges at the end of a method's signature.

You can fling an exemption, either a recently instantiated one or immunity that you immediately caught, by the throw keyword.

Try to appreciate the disparity amid throws and toss keywords, throws are utilized to postpone the managing of an ensured exception, and the bowl is used to appeal to an exception clearly.

The subsequent way declares that it bowls a RemoteException −

Example

import java.io.*;
public class className {

   public void deposit(double amount) throws RemoteException {
      // Method implementation
      throw new RemoteException();
   }
   // Remainder of class definition
}

A technique can state that it pitches more than one exemption, in which case the immunities are asserted in a list divided by commas. For instance, the subsequent method announces that it pitches a RemoteException and an InsufficientFundsException:

import java.io.*;
public class className {

   public void withdraw(double amount) throws RemoteException, 
      InsufficientFundsException {
      // Method implementation
   }
   // Remainder of class definition
}

The Finally Block

The last block pursues a try slab or a grab block. A last block of code always carries out, irrespective of the amount of an Exception.

Using the last block authorizes you to lope any cleanup-type reports that you desire to perform, no matter what ensues in the defended code.

The last block emerges at the end of the grasp blocks and has the subsequent syntax −

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");
      }
   }
}

This will produce the following result:

Output

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the following −

  • A grasp paragraph never survives with no a try report.
  • It is never needed to have final clauses when a attempt/catch lump is here.
  • The try hunk never be here without either grasp clause or lastly clause.
  • Any code never be here in between the try, grasp, finally blocks.

The try-with-resources

Usually, when we employ any reserves like flows, links, etc. we have to lock them openly using lastly block. In the following agenda, we are reading information from a file by FileReader and we are concluding it using 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();
         }
      }
   }
}

Try-with-resources also referred to as routine resource organization, is a new exemption handling mechanism that was initiated in Java 7, which mechanically closes the reserves used within the struggle catch block.

To employ this declaration, you simply require to stating the required resources inside the parenthesis, and the made resource will be locked mechanically at the end of the hunk. subsequent is the syntax of the try-with-resources statement.

Syntax

try(FileReader fr = new FileReader("file path")) {
   // use the resource
   } catch () {
      // body of catch 
   }
}

Following is the program that reads the data in a file using a try-with-resources statement.

Example

import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {

   public static void main(String args[]) {
      try(FileReader fr = new FileReader("E://file.txt")) {
         char [] a = new char[50];
         fr.read(a);   // reads the contentto the array
         for(char c : a)
         System.out.print(c);   // prints the characters one by one
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Subsequent summits are to be remembered while functioning with the try-with-resources account.

  • To employ a group with try-with-resources declaration it should apply AutoCloseable line and the close() way of it gets appealed to automatically at runtime.
  • You can state more than one group in the try-with-resources report.
  • While you state multiple classes in the try block of the try-with-resources statement, these groups are closed in undo order.
  • Except for the statement of resources within the parenthesis, all is the same as usual try/catch slab of a try block.
  • The resource stated in try obtains instantiated just previous to the creation of the try-block.
  • The reserve announced at the try lump is completely declared as closing.

User-defined Exceptions

You can generate your own exemptions in Java. Stay the subsequent points in intelligence when writing you possess immunity classes −

  • All immunities must be a teen of Throwable.
  • If you desire to write an ensured exemption that is mechanically implemented by the Handle or Declare Rule, you need to expand the immunity class.
  • If you desire to write a runtime exemption, you necessitate expanding the RuntimeException class.

We can describe our own exemption class as below:

class MyException extends Exception {
}

You just require to expanding the predefined exemption class to generate your have Exception. These are deemed checked exceptions. The subsequent InsufficientFundsException group is a user-defined exemption that expands the exemption class, making it a verified exception. An exemption class is like any other class, holding helpful fields and methods.

Example

// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception {
   private double amount;
   
   public InsufficientFundsException(double amount) {
      this.amount = amount;
   }
   
   public double getAmount() {
      return amount;
   }
}

To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount {
   private double balance;
   private int number;
   
   public CheckingAccount(int number) {
      this.number = number;
   }
   
   public void deposit(double amount) {
      balance += amount;
   }
   
   public void withdraw(double amount) throws InsufficientFundsException {
      if(amount <= balance) {
         balance -= amount;
      }else {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   
   public double getBalance() {
      return balance;
   }
   
   public int getNumber() {
      return number;
   }
}

The following BankDemo program demonstrates invoking the deposit() and withdraws() methods of CheckingAccount.

// File Name BankDemo.java
public class BankDemo {

   public static void main(String [] args) {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      
      try {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      } catch (InsufficientFundsException e) {
         System.out.println("Sorry, but you are short $" + e.getAmount());
         e.printStackTrace();
      }
   }
}

Compile all the above three files and run BankDemo. This will produce the following result

Output

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
         at CheckingAccount.withdraw(CheckingAccount.java:25)
         at BankDemo.main(BankDemo.java:13)

Common Exceptions

In Java, it is possible to define two categories of Exceptions and Errors.

  • JVM Exceptions − These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.
  • Programmatic Exceptions − These exceptions are thrown explicitly by the application or the API programmers. Examples: IllegalArgumentException, IllegalStateException.

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.