Java Program for Exception Handling in Java

Java Program for Exception Handling in Java

Exception handling is one of the most important topics in java. In this article, we have explained detail about exception handling in java and complete Java program for exception handling.

What is an exception?
The dictionary definition will tell us that exception is an anomalous condition, something that is different from usual and something unexpected.

So what does exception mean in programming?
It is basically a set of code or conditions that produce unexpected or illegal outputs.
For e.g.: c=a/b is a completely valid statement unless b=0. If b=0, an exceptional condition arises since the computer does not recognize infinity.

We may get errors at compile time or run time. Run time anomalies are called exceptions.

Types of Exception:

Exceptions are of two types:

  • Checked Exceptions
    The runtime exceptions that occur due to system related problems are called checked exceptions. The compiler will force us to handle them.
  • Unchecked Exceptions
    The exceptions that occur due to the logical mistakes of a programmer are called unchecked exceptions. They may go unnoticed since the compiler does not force us to handle them.

So now we know what an exception is but the question arises that why do we need to handle the exceptions?

Exceptions cause an unexpected termination of the program. This means that if in a code of 1000 LOC, and exception arises at say, line 19, no further lines of code shall be executed. The program terminates at line 19. To avoid this abrupt termination, we need to handle the exceptions.

 

Java Program for Exception Handling

Every type of exception is defined as a class in Java.
For e.g.: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException etc.

All of these exceptions are the sub-classes of ‘Exception’ class.
Every time an exception arises, an object of that particular exception class is created.

There are few basic techniques in Java program for exception handling:

  • Try-catch
  • Multiple catch
  • Universal catch
  • Throw
  • Throws
  • Finally

 

Try-catch Block

Try block, as the name suggests, contains the trial code. This means that any part of the code in which there are chances that an exception can occur is placed in the try block.
Once the exception is hit in the try block, it needs to be handled somewhere. The catch block catches the exception occurred in and thrown from the try block.
Now, the try block can throw exceptions only to the catch blocks that immediately follow it. Also, a catch block catches only the exceptions of a particular type whose object is specified in its parameters.

Syntax:

try
{
//Code that may cause an exception
}
catch (TypeOfException obj)
{
//Code to handle exception
}

Now there can be different types of exceptions in a particular try block. This brings the concept of multiple catch blocks.

 

Multiple Catch Blocks

When there is a possibility of more than one type of exception in the try block, the try block can be followed by multiple catch blocks. Whenever an exception arises, the object type is matched with the parameter of each catch block one after the other till a match is found.

Syntax:

try
{
//Code that may cause an exception
}
catch (ExceptionType1 obj)
{
//Code to handle exception
}
catch (ExceptionType2 obj)
{
//Code to handle exception
}
…
catch (ExceptionType_n obj)
{
//Code to handle exception
}

 

Universal Catch Block

We know that ‘Exception’ class is the superclass of all Exception classes.
So if we don’t know the type of exception that may arise, we can use Exception class instead of ExceptionType class for a catch block. Since it will catch all kinds of exceptions, it is called a universal catch block.

Syntax:

try
{
//Code that may cause any kind of exception
}
catch (Exception e)
{
//Code to handle all kinds of exceptions
}

 

Throw Keyword

Throw is mostly used for exception propagation.
If I call a function divide() from main() and an exceptional condition occurs in divide(), we can propagate the exception from divide() to main(). And the exception can be handled in main(). To propagate this exception, we need throw keyword.

Here is code for Java Program for Exception Handling:

public class ExceptionDemo1 {

public void divide(int a, int b)
{
try
{
System.out.println("Result is : "+(a/b));
}
catch(ArithmeticException e)
{
System.out.println("Caught first time.");
throw e;
}
}
public static void main(String[] args) {

ExceptionDemo1 obj= new ExceptionDemo1();
try
{
obj.divide(5,2);
obj.divide(2,0);

}
catch(ArithmeticException e)
{
System.out.println("Caught second time");
}
}

}

If you are Java programmer, you can find more article on java programming. It will help you to cement your expertise on Java domain.

Throws Keyword

It is used to handle multiple exceptions together. For example, if there are multiple possible exceptions in a function, any of them can be thrown back to the place where the function was called.

Syntax:

returntype function_name() throws ExceptionType1, ExceptionType2
{
//function code that causes exceptions
}
…
try
{
//function call
}
catch( Exception e)
{
// Code to handle exception
}

 

Finally Keyword

This is a block of code that will always execute irrespective of the fact whether an exception has occurred or not. It usually contains code that must always be executed like freeing memory, closing files, closing connections etc.
It usually follows try catch block.

Syntax:

try
{
//Code that may cause an exception
}
catch( Exception e)
{
// Code to handle exception
}
finally
{
//code that is always supposed to execute.
}

It is good practice to implement exception handling in java program, rather than program getting crashed unexpectedly. Hope this Java Program for Exception Handling will help you to get more detail insight. If you have any doubt feel free to comment below. I am happy to answer.

Leave a Reply

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