Java Programming

Exceptions Handling in Java and Types of Exceptions in Java

Exceptions in Java:

Exceptions in java are any abnormal conditions that may occur at runtime that may be file not found 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.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Java Exceptions Handling:

Java Exceptions handling is used to handle error conditions in an program systematically by taking necessary actions. In exception is an event that occurs during program execution, which makes further execution impossible, while exception handler. Piece of code that gets invoked when on exception Is occurred or encountered then this allow 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 for 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

class test
{
public static void main(String a[])
{
int x = 2;
int y= 0;
int res = x/y;
System.out.println(res);
}
}

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 at 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 java run time system.

Note: any exception which is not handled by the programmer will ultimately because processed by the default handler. In above example, when exception occur 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

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 exception to terminate normally

class test
{
public static void main(String a[])
{
try{
int x = 2;
int y= 0;
int res = x/y;
System.out.println(res);

}catch(ArithmeticException e)
{
System.out.println("division Error");
}

}
}

Exceptions handling

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

‘e’ is the object of type “ArithmeticException which receives the exception object. In 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 super class of all errors and exception in java language.

It is further divided to into subclasses

  1. Exception
  2. Error

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

Exceptions handling

Difference Between Exception and Error:

Exception:

An Exception is an abnormal condition. That occurs in a program which cause our program to terminate abnormally. when an exception occurs the jvm create an object (of class exception) that represents the abnormally 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 error is also a problem which is unrecoverable that occurs when a program is running. When an error occur during program execution an object is created of class error this object represents an error which is unrecoverable and 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.

Throwable Hierarchy:

Exceptions handling

Types of Exceptions handling in Java:

There are two types of Exceptions

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

Checked Exception:

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:

all those Exceptions handling of class  RuntimeException (and its subclasses) and class Error are unchecked Exceptions handling. These exception are called unchecked. These exception are checked at runtime not at compile time. the unchecked exception compiler do not force the programmer to handle the exception two means that these exception are caught by java interpreter not compiler. To handle the unchecked Exceptions handling we just put our code (that have 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:

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 in java programming:

class test
{
public static void main(String a[])
{
try{
int x = 12;
int y= 0;
int res = x/y;
System.out.println("this code will not executes");

}catch(ArithmeticException e)
{
System.out.println("division Error");
}
System.out.println("after catch statement");

}
}

Exceptions handling

Catch Block:

Thrown exception is caught in catch block and handle the exception. An object (exception) which represent 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:

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 programming:

class test
{
public static void main(String args[])
{
try{
int a = args.length;
System.out.println("a="+a);
int x= 10/a;
int c[]={1};
c[40]=90;

}catch(ArithmeticException e)
{
System.out.println("division Error");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("You Specified invalid array index");
}

System.out.println("After Maltiple catch block statement");

}
}

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 screen

Exceptions handling

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

Finally Block:

Finally block {} is always executed if 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 programming:

class test
{
public static void main(String args[])
{
int result = division(20,0);
System.out.println("result = " + result);
}

public static int division(int x, int y)
{
int quotient = -1;
try
{
quotient = x/y;
}
catch(ArithmeticException e)
{
System.out.println("Division Error");
}
finally
{
if(quotient !=-1)
{

System.out.println("Finally Block execute");
System.out.println("Result "+ quotient);
}
else
{
System.out.println("finally Block executed but exception occured");
return quotient;
}
return quotient;

}

}

}

Exceptions handling

Throwing an Exception:

As far as we have only been catching exception that are thrown by the java run  time system. Whenever exception raised java runtime automatically create an exception object and throw 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 exception. The flow of execution stops immediately after the throw statement any subsequence 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 match control Is transfer to that statement if no matching catch is found then default. The default handler exception handle it.

class test
{
public static void main(String args[])
{
int age = 10;
try{

if(age<20)
throw new Exception();
else
System.out.println("hi, old Person");
}
catch(Exception oops)
{
System.out.println("So young one");

}
}

}

Exceptions handling



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 to use throw clause:

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

Exceptions handling

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

For example we have write 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 put 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 Throws Exception clause in java programming:

class test
{
public static void main(String args[])
{
try{
method1();
}catch(ArithmeticException e)
{
System.out.println("Division by Zero Error");
}

}
public static void method1() throws ArithmeticException
{
method2();
}

public static void method2() throws ArithmeticException
{
int x, y, res;
x=10;
y=0;
res=x/y;
}
}

Exceptions handling

Chained Exceptions 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 describe 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 chained exception handling in java:

class test
{
static void demo()
{
NullPointerException e = new NullPointerException("tp layer");
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[])
{
try
{
demo();
}
catch(NullPointerException e)
{
System.out.println("caught" + e);
System.out.println("Orignal cause" + e.getCause());

}

}

}

Exceptions handling

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.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

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

Back to top button