Posted in:

Exception Handling in Java

Java being the most prominent object-oriented language provides a powerful mechanism to handle errors and exceptions, and effective exception handling makes your program more robust and easier to debug.

Now we will discuss what exactly the exception is.

An exception is a problem that occurs during the execution of a program. It can take place for many different reasons, like a user has entered an invalid data or a file that needs to be opened cannot be found, or you can also say that a network connection has been lost in the middle of communication, or the JVM has run out of memory. But if we do not handle them, it leads to a system failure.

So exception handling in Java is very important, and that’s where Java introduced an exception handling mechanism to handle the runtime errors so that the normal execution flow will not be, for example, glass not found our exception SQL exception, etc. 

Now let’s move ahead and see the difference between error and exception.

  • Errors are impossible to recover, but an exception can be recovered by handling them.
  • Errors are of type unchecked, but exceptions can be either checked or unchecked type.
  • Exceptions and errors are something that happened at runtime.
  • An exception is caused by the application itself, whereas errors are caused by the environment in which the application is running.
  • Exceptions are caused by the program, whereas Errors are caused by the system.

There are mainly three types of errors in Java programming:

  • Syntax errors
  • Logical errors
  • Runtime errors – also called exceptions

Commonly Occuring Exceptions

There are few commonly occuring exceptions in java:

  1. Arithmetic Exception
  2. Illegal Argument Exception
  3. Null pointer Exception
  4. Number Format Exception
  5. Array Index out of Bound Exception

Exceptions and their meaning:

  • ClassNotFoundException: It means class is not found.
  • InstantiationException: It means attempt to create an object of an abstract class or interface.
  • InterruptedException: In this type of exception one thread has been interrupted by another thread.
  • NoSuchFieldException: It means a requested field does not exist.
  • NoSuchMethodException: It means a requested method does not exist.

Why does an exception occur?

  • User error
  • Programmer error
  • Resources error

For example:

package mainn;

import java.util.*;

public class Great

{

public static void main(String args[])

{

int a=10, b=0, c;

c= a/b;

System.out.println(c);

}

}

This example will throw a runtime error.

In exception handling, as the term says, it handles the exceptions. It is a mechanism to handle run time errors.

Advantages of Exception handling

  • It maintains the normal flow of the program.
  • Meaningful error reporting.

The main purpose of handling the exception is to detect and report an exception so that proper action can be taken and prevent the program, which automatically terminates or stops the execution because of that exception. The throwable class has a subclass which is the exception class. Error is also another subclass that is derived from the Throwable class.

The object orientation mechanism has provided the following technique to work with exception:

  1. try
  2. catch
  3. throw
  4. throws
  5. finally

try and catch block:

  • Try block is used to enclose the code that might throw an exception and will be handled by the catch block. It must be used within the method of a class.
  • It must be followed by either catch or finally block.
  • When an exception occurs in a program, that exception is handled by a catch block. A catch block must be used after the try block only.
  • A catch statement includes declaring the type of exception you are trying to catch.

Syntax:

try

{

Code that may throw exception

}

catch (Exception Name e)

{

Catch block

}

 

Nested try statements:

The try statement can be nested. That is, a try statement is often inside a block of another try. When a try statement is entered, its corresponding catch block has to be entered. 

Catching multiple exceptions:

Sometimes there may be a chance to have multiple exceptions in a program. We can use multiple catch blocks with a single try to handle multiple exceptions. At a time, just one exception occurs, and at a time, just one catch block is executed. There should not be any relation between sorts of exceptions in multi-catch blocks (either child to parent or parent to child or same type); otherwise, we’ll get a compile-time error.

Exception Propagation:

Inside a method, if an exception is raised and if you are not handling that exception, then the exception object will be propagated to the caller, then the caller method is responsible for handling the exception. This process is called exception propagation.

Example:

void getdata( )

{

getdata1( );

}

void getdata1( )

{

getdata2( );

}

void getdata2( )

{

int a = 100/0;

}

Throw:

  • The java throw keyword is employed to explicitly throw an exception.
  • We can throw either checked or unchecked exceptions in java using the throw keyword. The throw keyword is especially used to throw a user-defined exception.
  • The programmer is creating an exception object and handing it over to JVM.

Syntax:

throw new ExceptionName;

The purpose of throw keyword is to handover created exception objects to the JVM manually.

Throws:

If you don’t want to explicitly catch an exception and you just want to declare that your method throws the exception. This passes the responsibility to handle the exception to the method that invoked your method. This is done by using the throw keyword. If you invoke a method that declares an exception, then you must either catch or declare the exception.

Syntax:

return_type method_name( ) throws ExceptionName

{

occurs exception;

}

  • Throws required only for checked exceptions and if we use throws for unchecked exceptions there will be no impact.
  • Throws is required only to assure compiler and use of throws keyword doesn’t prevent abnormal termination of the program.
  • It is mandatory to use the try catch over throws keyword.
  • Throws keyword can be used for methods and constructors but it is not used for classes.
  • throw keywords are often used just for throwable objects and if we use normal java classes then we will get compile time errors like incompatible types.

Finally:

  • The Finally block is a block that is used to execute important code such as closing files etc.
  • This finally block is usually executed whether you handled the exception or not.
  • Finally block should be the last block of execution in the program.
  • At least one block either catches or finally must be associated with each try block. In case you have both catches and finally block with the same try block, you must put finally block after all catch blocks.
  • There is only one finally block for each try block and there can be zero or more catch blocks.
  • The finally block won’t be executed if the program quits (either by calling System.exit( ) or by causing a fatal error that causes the method to abort).

Try with resources:

  • It is very suggested to write down finally block to close resources which are open as a part of try block till java 1.6 version.
  • The problem in this approach is the programmer is required to close the resources inside the finally block. It increases the complexity of programming.

We have to write finally block mandatory and hence it increases the length of the code.

  • To overcome the above problems java introduced try with resources in java 1.7 version.
  • The major advantage of try with resources is resources which we open as a part of try block will be closed automatically once control reaches end of try block either normally or abnormally and hence there is no requirement to close explicitly so that complexity of programming will be reduced.
  • There is no requirement to write finally block.

Try with multiple resources:

We can declare multiple resources and these resources should be written with a semicolon between them.

try( Resource1; Resource2 )

{

}

User defined exception:

  • These exceptions need to inherit or extend the exception class in order to act as an exception.
  • Throw keyword is mainly used in such exceptions.

Re -throwing exception:

We can use this approach to convert one exception type to a different exception type.

For example,

try

{

int a=100/0;

}

catch (ArithmeticException e)

{

throw new NullPointerException;

}

Difference between throw and throws:

  • Java throw keyword is used to explicitly throw an exception whereas throws keyword is used to declare an exception.
  • Checked exceptions cannot be propagated using throw only but with throws keyword checked exceptions can be propagated.
  • Throw is followed by an instance whereas throws is followed by class.
  • Throw is used within the method but throws keyword is used with the method signature.
  • You cannot throw multiple exceptions with throw keyword but you can declare multiple exceptions with throws e.g. 

public void method ( ) throws IOException,ArithmeticException

Best practices with exceptions:

  • Do not catch an exception if you can’t affect it.
  • Always use finally to perform pack up activities.
  • Name custom exceptions appropriately.
  • Do not throw multiple exceptions from a method.
  • Use wrappers where necessary.

Hope this article helps you a lot for understanding this topic. If you’re interested in free online courses with certificates, So enroll today on Great Learning Programme.