Java

Exception Handling in Java and Types of Exceptions in Java

Exceptions in Java:

Exception handling- Exceptions in java are any abnormal conditions that may occur at runtime that may be file not found an exception. Division by zero exception is wrong input exception etc. on such condition java throws an exception object. Exceptions are basically java objects during the exception our program halts, hanged, or dominated abnormally. to control such situations we use java exception handling.



Java Exception Handling:

Java Exception handling is used to handle error conditions in a program systematically by taking necessary actions. An exception is an event that occurs during program execution, which makes further execution impossible, while an exception handler. Piece of code that gets invoked when on exception Is occurred or encountered then this allows the program to either fix. Whatever caused by the exception and output an appropriated error message and then cause program execution to gracefully terminate.

Considering the following example showing an exception without handling it.

The following intentionally cause a divide by zero error what will happen when the following program is not handled

When the above program executes ad when the control comes to line no, 7 the java run time system detects the attempt to divide by zero. It will construct or create a new exception object and then throws this exception and will stop execution further and terminate the program. In this example we have not supplied any exception handler of our own, so the exception is caught by the default handler (automatically handler) provided by the java run time system.

Note: any exception which is not handled by the programmer will ultimately because processed by the default handler. In the above example, when an exception occurs at line no, 7 then the default handler displays a string describing the exception, print a stack trace from the point at which the exception occurred, and terminate the program.

The following output generated by the JDK (java development kit) interpreter.

Exceptions handling in java

Stack trace showing the class name “test.main” showing error in the main class test at line no, 7.

Now the following program with appropriate handling of the exception to terminate normally

Exceptions handling in java

This object is thrown exception to the handler which is “catch” which executed the object having exception. In catch arrangements, ArithmeticException is a subtype of class Exception.

‘e’ is the object of type “ArithmeticException which receives the exception object. In the catch block we manually code with a message indicating about error then program after catch block will terminate normally.


Throwable Class:

The throwable class is the superclass of all errors and exceptions in java language.

It is further divided to into subclasses

  1. Exception
  2. Error

Exception and Error are the subclasses of the superclass throwable. These subclasses are also further subdivided to further subclasses.

Exceptions handling in java

Difference Between Exception and Error:

Exception:

An Exception is an abnormal condition. That occurs in a program which causes our program to terminate abnormally. when an exception occurs the JVM create an object (of class exception) that represents the abnormal condition. A program can use this object to recover from the problem.

Example of exception:

Division by zero

Nullpointer exception

Invalid away indexing

Error:

While the error is also a problem that is unrecoverable that occurs when a program is running. When an error occurs during program execution an object is created of class error this object represents an error that is unrecoverable and the program must stop.

Example:

StackOverflow

out of memory error

awt error

in short, the main difference between exception and error is that program can recover from an exception but a program cannot recover from an error.

Exception Handling Throwable Hierarchy:

Exceptions handling in java


Types of Exception handling in Java:

There are two types of Exceptions

  • Checked Exception (compile exception)
  • Unchecked Exception (run time exception)

Checked Exception Handling:

All those exception except RuntimeException (and its subclasses) and Error are checked exception, including exception class itself is checked exception. Checked exception means that these exception are checked at compile time we should compulsory handle the checked exception otherwise compile time error will be generated.

There are two ways to handle the checked exception.

  1. Declare the exception using throws clause

e.g

public void methodName()

throws

exceptionName;

  1. Put the exception code in try block.

Example:

IOExceptio

ClassNotFoundException

IllegalAccessException

FileNotFoundException

Unchecked Exception Handling:

all those Exceptions handling of class  RuntimeException (and its subclasses) and class Error are unchecked Exceptions handling. These exceptions are called unchecked. These exceptions are checked at runtime, not at compile time. the unchecked exception compiler do not force the programmer to handle exception two means that these exceptions are caught by the java interpreter not compiler. To handle the unchecked Exceptions handling we just put our code (that have a chance to create exception) in try block.

Example:

Dividing by zero

NullPointerException(such as trying to access an object through a null reference)

IndexOutOfBoundException( trying to access the element of array beyond its boundary) are unchecked Exception.

Try Block Exception Handling:

The java code that you think may produce an exception in placed within try block to handle the error. If no exception occur in try block the exception proceeds. It exception occur in try block it automatically create an object of class exception then try block automatically throw this object to the appropriate handler i.e. catch block. If the matching handler (catch) not found the exception proceeds and the default exception handler throws an exception and program terminates abnormally. if the exception generated within the try block the remaining statements in the try block will not execute. When a control pass (if exception occur) from try block to the handler block then control will not back to the try block.



Example: how to use try block exception handling in java:

Exceptions handling in java

Catch Block Exception Handling:

The thrown exception is caught in the catch block and handle the exception. An object (exception) which represents the exception case sent from the try block and caught by the catch block to catch the exception we declare the exception or exception-type as its argument to catch the exception.

e.g.

catch(ExceptionType object)

{

Handling code;

}

Multiple catch block Exception handling:

In some situations more than one exception could be raised by a single piece of code to handle more than one exception we use multiple catch blocks, the following example will clear the concept of multiple catch block.

Example: how to use multiple catch block in java for exception handling:

This program will cause a “division by zero error” with no command-line argument. Since ‘a’ will be zero to cause exception of “division by zero”

Consider if we type in command line C:\Users\Fawad khan\Desktop\java>java test and press enter the following output will be displayed on the screen

Exceptions handling in java

And if we provide an extra command line argument then a=1 but the out of bound exception will be raised. Consider if we type in command line C:\Users\Fawad khan\Desktop\java>java test fawad and press enter the following output will be displayed on screen

 

Exceptions handling in java


Finally Block Exception Handling:

Finally block {} is always executed if an exception occurred or not generally finally {} block is used for freeing resources cleaning up closing connection (usually with DB).

Why finally block is used:

Suppose if an exception occurred in try {} block the statement below the exception will never execute so we want to execute these statements must in any case so in that situation we use finally {} block.

What does mean by freeing resource, closing connection, cleanup code:

As we discus above that the finally {} block is used for freeing resources cleaning up closing connection (usually with DB) this mean that when an exception occurs execution stops and control is given to the appropriate handler. This means that some line of code you expect to always be executed for example if you have open a file and closing statement is also in try {} block so if exception occurred the closing file statement will not execute. So this code must be write in finally block.

A database connection is also another example for being closed in finally block. Because the number of connections allowed to a DB server is sometimes limited it is important to close DB connection as quick as possible. If an exception is thrown before you can close your connection so it is important to place the closing connection code in finally {} block.

Example: how to use finally block in Java for exception handling:

Exceptions handling in java


Throwing an Exception Handling:

As far as we have only been catching an exception that is thrown by the java run time system. Whenever an exception raised java runtime automatically creates an exception object and throws it to the appropriate handler.

It is also possible that you can explicitly throw an exception and by java run time system. The general syntax to use thrown in java is

Throw throwableInstance;

Here throwableInstance must be an object of type throwable or a subclass of throwable. Simple types such as int, float, String cannot be used as an exception. The flow of execution stops immediately after the throw statement any subsequent statements are not executed. The nearest enclosing try{} block is inspected to see if it has a catch statement that matches the type of exception if it does find a matched control Is transfer to that statement if no matching catch is found then default. The default handler exception handle it.

Exceptions handling in java

Throws Exception clause:

The “throws” clause is used with the header of the method.

e.g.

void func() throws ExceptionType..

{

Program Body;

}

And must here to define the type of exception with throws clause which it might throw.



Why use throw clause:

When an exception raised in a method and that method want that I do not want to handle with the exception, this exception should be handled from where this method is called in that situations we use the throws clause consider the following example

Exceptions handling in java

As we know that java runtime system calls main() method automatically where main() method in turns call other methods.

For example, we have written a code in method2 which can produce Exceptions handling suppose some exception raised in method2 and method2 want that I do not want to deal with this exception it should deal method1 where method2 is called in that situation when putting throws clause with method2.

e.g.

public void method2() throws Exception

{

Program body;

}

Now this exception is then passed to method1 so if we want to deal or handle with this exception, then simply put method1() in try block with it appropriate handler.

If we do not want to handle it also in method1 then similarly put throws clause with method1 so that to handle this exception in a method where method1 is called.

Here main() method calls method1 so if you want to handle it in main() then use try catch block to handle it. If you do not want to handle it also in main() then similarly put throws clause with main() method, so this will pass the exception to the default handler (Java runtime system). So here the default handler will deal with this exception abnormally.

Example: how to use throw clause in java for exception handling:

Exceptions handling in java

Chained Exception handling:

Java 2 version 1.4 added a new feature to the exception subsystem ie chained exception. This is a technique of handling exceptions by re-throwing a caught exception, it means the chained exception feature allows yu to associate another exception with an exception. This 2nd exception describes the cause of the first exception.

For example imagine a situation in which a method throws an ArithmeticException because of an attempt to divide by zero however the actual cause of the problem was that an IO error occurred which caused the divisor to be set improperly although the method must certainly throw an ArithmeticException, since that is the error that occurred.

Chained Exceptions handling let you handle, this and any other situations and also let it you the calling code know what the underlying cause was IO error.

To allow chain exception java 2 version 1.4 added two constructors and two methods to throwable the constructors, which are:

Throwable( throwable causeExc)  

The first constructor in the form, causExc is the exception that cause the current exception i-e causeExc is the underlying reason that on exception occurred.

Throwable(String msg, Throwable causeExc):

The 2nd constructor is of the form you can specify the description at the same time that you want to specify a cause exception these two constructor are also added to the error exception and runtimeException classes.

The chained exception has included two methods in throwable class which are:

Throwable getcause():

The getCause() method returns the exception that underlies the current exception if there is no underlying exception null is returned.

Throwable initCause(Throwable causeExc):

The initCause() method associates “causeExc” with the invoking exception and returns a reference to the exception.



Example: how to use getcause and initCause method and constructor of chained exception handling in java:

Exceptions handling in java

Code explanation:

In step 5 we intentionally create an exception of type NullPointerException and assign its reference to object e. then we add a cause due to which exception is raised and mention or specify message of cause in argument as a string in short we associate Arithmetic exception with NullPointerException object e with cause.


Related Article:

https://programmingdigest.com/java-type-conversion-or-java-type-casting/

Related Articles

Leave a Reply

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

Back to top button