Introduction

  • An exception is a condition that causes a problem, which stops program execution suddenly and abnormally, from continuation from the point of occurrence of it.

Definition

  • Exceptions are events and runtime hidden errors that arise suddenly and disrupt the normal flow of a program’s instructions during runtime which may lead to program termination or incorrect or partial results.

Reason/Cause of Exception

  • These events can occur at run time due to various reasons or some abnormal condition arising in the program suddenly, such as invalid user input, hardware failures, network issues, etc.

Precaution for Exception

  • When an exception is caught in the program, the following things can be done as precautions:
    • Problem/Exception must be fixed which is the first and major thing for smooth program execution.
    • Use proper exception handling code for any OOPs code even if they may or may not arise exceptions.
    • If not possible, Do something else to manage the problem instead of avoiding the problem/exception.
    • If not manageable, exit the application using System.exit() method.
    • If possible, Re-throw the exception to some other method or portion of code that does not produce a fatal error condition.
    • If not handled, throw a new exception to replace the previous one.
    • If nothing looks good, return a default value/situation (a non-void/return type method – the traditional way of handling exceptions).
    • Engulf the exception in a less important method and finally come out from the method (in a void method).
    • Don’t give importance to the exceptions if they are not so fatal for our program.
    • Engulf the exception and continue in the same method as normal, if the program is not so sensitive or important(Rare but dangerous to use it).

Features/Characteristics

  • Java run time system exceptions throw system-generated exceptions automatically to the catch block from the source codes of the try block.
  • Exceptions suddenly arise as hidden errors and usually are not identified by even developers or in compile time.

Syntax

try 
{ //main programming Source codes } catch (ExceptionType instance)
{ // catch block exceptional handling codes } finally
{ // finally block always executable codes }

Advantage

  • Exception handling provides a safe escape route from problems or clean-up of error handling code.

Disadvantage

  • Exception stops the program from continuing further abnormally(if not handled properly) as it arises because of a lack of information to deal with the exception condition.

Use/Functions

  • Exception handling in Java allows one to manage and recover from exceptional conditions.
  • Exception handling makes a program reliable, efficient, and effective in outcome.

Components of Exceptions

  • Exceptions in Java are properly handled (usually not removed) by the use of five keywords completely: try, catch, finally, and throw, throws keyword. 

The try block

    • This block generally contains the main programming statements/source codes of the program on which we want to monitor for exceptions, in the try block.
    • An exception arises inside this block and is then thrown from here for a catch block.
    • If none of the statements in the try block generates an exception, the catch block is skipped.
    • A try block must be followed by at least one catch block.
    • There is usually one try block in a program but it may be more than one (according to a program structure) as in a nested try statement.
    • This is a compulsory block of the exception handling.

The catch block

    • This block handles any exception that arises in the try block by matching and catching it.
    • Normally at least one catch block must be in a program to handle exceptions.
    • If any exception occurs in a try block they will be generally/specifically caught using a catch block.
    • The catch block catches the exception and statements inside the catch block are executed accordingly.
    • There may be at least one or more than one catch statement in the program.
    • The catch block cannot be used without the try block.
    • This is a compulsory block of the exception handling.
    • Multiple Catch
      • Sometimes there is a chance of multiple specific exceptions arising in a try block of code of a program. For this, we can use multiple catch clauses to catch the different kinds of exceptions that the code can throw. To handle these exceptions, more than one catch clause/area/block is used to handle each specific exception. When an exception is thrown, different catch blocks associated with the try block check the thrown order and identify the first, one whose type (the exception type passed as an argument in the catch clause), matches the exception type and when matched then executed finally.
      • In Multiple catch situations, only one exception occurs at a time and only one catch block is executed successfully.
      • All catch blocks in multiple catch situations must be ordered from most specific to most general form.
      • Each catch block in multiple catch situations must have a different exception handler to handle different types of exceptions separately.

The finally block

    • In Java, the finally block is always executed no matter whether there is an exception or not.
    • A final clause is included in a program in the last block of execution in the program.
    • If an exception occurs, the finally block is executed after the try…catch block. Otherwise, it is executed after the try block. For each try block, there can be only one finally block.
    • This is an optional block of the exception handling.
    • It is a good practice to use the finally block. It is because it can include important cleanup codes like,
      • code that might be accidentally skipped by return, continue, or break.
      • closing a file or connection.

Throw Keyword

    • The Java throw keyword is used to explicitly throw a customized single exception.
    • When we throw an exception, the flow of the program moves from the try block to the catch block.
    • syntax:
      throw throwableObject;
      (Here
      a throwable object is an instance of class Throwable or subclass of theThrowableclass.)

Throws Keyword

    • The throws keyword is used to declare the type of exceptions that might occur within the method. It is used in the method declaration.
    • We can throw multiple exceptions using the throws keyword.
    • Syntax:
      accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … 
      { // related Exceptoion codes }

Working Mechanism of Exception Handling

  • When an exception occurs, it is caught by the catch block. The catch block cannot be used without the try block.
  • To catch an exception successfully in Java, we write code inside a try block with one or more catch clauses as needed. Here, each catch clause specifies one exception type to handle it properly. If an error arises in the try block code at run time it throws an exception, the associated catch clauses will be examined by the Java virtual machine. If the virtual machine finds a catch clause that is prepared to handle the thrown exception, the program continues execution starting with the first statement of that catch clause, and the catch block is used for executing code to handle the exception and graceful termination of the program.

Types of Exception Handling

  • There are two categories of exceptions in Java –
    • Checked Exception
    • Unchecked Exception
    • Checked Exception/Compile Time Exceptions –
      • When the Java compiler and the JVM both check the Java source code to make sure that the rules of Java are obeyed fully or not, is called a checked exception.
      • Checked exceptions must be handled at compile time.
      • Checked exceptions are those that cannot be ignored rather than handled properly otherwise the program will terminate abnormally.
      • All exceptions instantiated from the Exception class or its subclasses are of this nature.
      • Examples are – IOException, InterruptedException, Environmental errors ( that cannot necessarily be detected during testing such as disk full, broken socket, database unavailable, etc), VirtualMachineErrors (such as ClassNotFound, OutOfMemory, NoSuchMethod, IllegalAccessToPrivateField, etc).
    • Unchecked/Runtime Exceptions –
      • These are exceptions which are not checked at compile-time but at run-time.
      • For example – ArithmeticExceptionNullPointerExceptionArrayIndexOutOfBoundsException, IllegalArguments, exceptions under Error class, etc.
      • In other words, Programming errors that are detected during the testing time of Java programs are of this nature.
      • Usually, we don’t need to handle unchecked exceptions. It’s because unchecked exceptions occur due to programming errors. And, it is a good practice to correct them instead of handling them. Run time exceptions do need to be handled and are handlable.
      • Most of the run time exceptions are thrown by the Java virtual machine(JVM) itself.
      • They are the members of the RuntimeException family.
      • These exceptions are usually an indication of software bugs.
      • It is those types of exceptions in which we have an option to handle it or ignore it. When we select to ignore the possibility of an unchecked exception, then, as a result of that the program will terminate. When we select to handle an unchecked exception that occurs then the result will depend on the code that we have written to handle the exception.
      • All exceptions instantiated from the RuntimeException class or its subclasses are of this nature.

List of Important Java Exceptions and Their Reason

Slno Exception Name Examples
01. ArithmeticException Division by zero or some other kind of
arithmetic problem
02. ArrayIndexOutOfBoundsException An array index is less than zero or
greater than or equal to the array’s
length
03. FileNotFoundException Reference to a file that cannot be found
04. IllegalArgumentException Calling a method with an improper
argument
05. IndexOutOfBoundsException An array or string index is out of
bounds
06. NullPointerException Reference to an object that has not been
instantiated
07. NumberFormatException Use of an illegal number format, such
as when calling a method
08. StringIndexOutOfBoundsException A String index is less than zero or
greater than or equal to the String’s
length

Exception Hierarchy in Java

  • All exceptions that occur in Java programs are a subclass of built-in class
    Throwable. Two classes Exception and Error are subclass of Throwable class. Exception class is used to handle exceptional conditions. Error class defines those exceptions which are not expected by the programmer to handle.
  • class java.lang.Object
    |
     class java.lang.Throwable
    |
    class java.lang.Exception + class java.lang.Error

Loading

Categories: Java

0 Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.