Exception Handling In Java Language

EXCEPTION HANDLING :

An exception is an event, which occurs during the execution of the program, that an interrupt the normal flow of the program’s instruction. In other words, Exceptions are generated when a recognized condition, usually an error condition, arises during the execution of a method. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions.

For each method that could throw an exception, your code must report to the Java compiler that it could throw that exact exception. The compiler marks that method as potentially throwing that exception, and then need any code calling the method to handle the possible exception.

Exception handling is basically use five keyword as follows :

  • try
  • catch
  • throw
  • throws
  • finally

OVERVIEW :

Exceptions are generated when an error condition occur during the execution of a method. It is possible that a statement might throw more than one kind of exception. Exception can be generated by Java-runtime system or they can be manually generated by code.

Error-Handling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as

  • Run out of memory
  • Resource allocation Error
  • Inability to find a file
  • Problems in Network connectivity.

In this unit we will learn the exception handling mechanism.

WHAT IS EXCEPTIONS AND HANDLING EXCEPTION :

Exceptions are generated when a recognized an error condition during the execution of a program. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions

  • for each method that could throw an exception, your code must report to the Java compiler that it could throw that exact exception.
  • the compiler marks that method as potentially throwing that exception, and then need any code calling the method to handle the possible exception.

There are two ways to handle an exception:

  • you can try the "risky" code, catch the exception, and do something about it, after which the transmission of the exception come to an end
  • you can mark that this method throws that exception, in which case the Java runtime engine will throw the exception back to the method.

So, if you use a method in your code that is marked as throwing a particular exception, the compiler will not allow that code unless you handle the exception. If the exception occurs in a try block, the JVM looks to the catch block(s) that follow to see if any of them equivalent the exception type. The first one that matches will be executed. If none match, then this methods ends, and execution jumps to the method that called this one, at the point the call was made.

Following image shows the Exception type.

partial view of the Throwable family in java

An error means fault and there are two types of error as follows:

Compile time errors :

Compiler time error means Java compiler identify the syntax error at the time of compilation. And without successfully compilation, compiler does not create .class file. That means we have to compile the program which should be error free and then compiler creates .class file of the program and then we can run the program.

The common problems are:

  • Missing braces
  • Missing semicolon
  • Missing double quote in string
  • = instead of == operator

And so on.

CODE/PROGRAM/EXAMPLE
//For example:
class Try1
{
public static void main(String args[])
{
int a=12;
int b=0;
int c=a/b
System.out.println("Division is+c);
}
}

// O/P : C:\cc>javac Try1.java
Try1.java:8: ‘;’ expected
System.out.println("Division is+c);
^
Try1.java:8: unclosed string literal
System.out.println("Division is+c);
^
2 errors

Run time errors :

Several time program may compile successfully and compiler creates the .class file of the program but when the time of running the program, it shows the error and that type of error called run time error.

The common problems are :

  • Divide by zero
  • Conversion of invalid string to number
  • access the element that is out of bound of an array
  • Passing the parameters with invalid range.
  • And so on.
CODE/PROGRAM/EXAMPLE
//For example :
write a program to find out division of two numbers.
class Try1
{
public static void main(String args[])
{
int a=12;
int b=0;
int c=a/b;
System.out.println("Division is"+c);
}
}

// Output:
C:\cc>javac Try1.java
C:\cc>java Try1
Exception in thread "main" java.lang.ArithmeticException: /
by zero at Try1.main(Try1.java:7)

try…catch :

If a method is going to resolve potential exception internally, the line of code that could generate the exception is placed inside a try block

  • there may be other code inside the try block, before and/orafter the risky line(s) - any code that depends upon the risky code's success should be in the try block, since it will automatically be skipped if the exception occurs
Syntax
//Syntax –
try
{
code
risky/unsafe code
code that depends on the risky code succeeding
}

There is usually at least one catch block immediately after the try block

  • a catch block must specify what type of exception it will catch
Syntax
//Syntax –
catch (ExceptionClassName exceptionObjectName)
{
code using methods from exceptionObjectName
}
  • there can be more than one catch block, each one marked for a correct exception class
  • the exception class that is caught can be any class in the exception hierarchy, either a general (base) class, or a very correct (derived) class
  • the catch block(s) must handle all checked exceptions that the try block is known to throw unless you want to throw that exception back to the method.
  • it is possible to have a try block without any catch blocks if you have a finally block but any checked exceptions still need to be caught, or the method needs to declare that it throws them

If an exception occurs within a try block, execution jumps to the first catch block whose exception class matches the exception that occurred. Any steps remaining in the try block are skipped. If no exception occurs, then the catch blocks are skipped.

If declare a variable within a try block, it will not exist outside the try block, since the curly braces define the scope of the variable. You will often need that variable later, if nowhere else other than the catch or finally blocks, so you would need to declare the variable before the try.

If you declare but don't initialize a variable before a try block, and the only place you set a value for that variable is in the try block, then it is possible when execution leaves the try ... catch structure that the variable never received a value.

So, you would get a "possibly uninitialized value" error message from the compiler, since it actually keeps track of that sort of thing. Usually this happens with object references; you would also generally initialize them to null.

CODE/PROGRAM/EXAMPLE
public class demo
{
public static void main(String[] args)
{
int ans1, ans2;
int a = 2, b = 2, c = 0;
try
{
ans1 = a/b;
System.out.println("a/b = " + ans1);
ans2 = a/c;
System.out.println("a/c = " + ans2);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic
Exception!");
}
System.out.println("demo is over");
}
}

// Output:
C:\>set path=C:\Java\jdk1.5.0_01\bin
C:\>javac demo.java
C:\>java demo
a/b = 1
Arithmetic Exception!
demo is over

Code Explanation –

The program will print the first result, and then not succeed while performing the division for the second equation. Execution will step to the catch block to print our message on the screen

//Example - The prior example used a RuntimeException, which your code is not obligated to handle. Most methods in the I/O classes throw IOException, which is an exception that you must handle. Following program shows the use of IOException.

CODE/PROGRAM/EXAMPLE
import java.io.IOException;
public class demo
{
public static void main(String[] args)
{
int num = 0;
num = System.in.read();
try
{
num = System.in.read();
System.out.println("You entered " + (char) num);
}
catch (IOException e)
{
System.out.println("IO Exception occurred");
}
}
}

// Output:
C:\>javac demo.java
demo.java:11: unreported exception java.io.IOException; must be
caught or declared to be thrown
num = System.in.read(); // comment out this line
^
1 error

Code Explanation :

The line marked to comment out throws IOException, but is not in a try block, so the compiler rejects it. The second read attempt is within a try block, as it should be.

  • there is no way we can force an IOException from the keyboard to test the catch block.

Using Multiple catch Blocks It is possible that a statement might throw more than one kind of exception

  • you can list a sequence of catch blocks, one for each possible exception
  • remember that there is an object hierarchy for exceptions –
CODE/PROGRAM/EXAMPLE
class demo
{
public static void main (String args [])
{
int A[ ] = new int [5];
try
{
for (int c = 0; c <5; c++)
{
//do nothing
}
for (int c = 0; c <5; c++)
{
A[c] = c/ c;
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("Array out of bound ");
}
catch (ArithmeticException e)
{
System.out.println ("Zero divide error");
}
}
}

// Output:
C:\>javac demo.java
C:\>java demo
Zero divide error
C:\>

Finally Block :

To guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try and catch blocks The code in the finally block will almost always execute, even if an unhandled exception occurs; in fact, even if a return statement is encountered

  • if an exception causes a catch block to execute, the finally block will be executed after the catch block
  • if an uncaught exception occurs, the finally block executes, and then execution exits this method and the exception is thrown to the method that called this method
Syntax
//Syntax –
try
{
risky code/ unsafe code block
}
catch (ExceptionClassName exceptionObjectName)
{
code to resolve problem
}
finally
{
code that will always execute
}

Throwing an Exception :

You can throw an exception explicitly using the throw statement.

Example : You need to throw an exception when a user enters a wrong student ID or password.

The throws clause is used to list the types of exception that can be thrown in the execution of a method in a program.

Using the throw Statement

  • 1. The throw statement causes termination of the normal flow of control of the java code and prevents the execution of the subsequent statements.
  • 2. The throw clause convey the control to the nearest catch block handling the type of exception object throws.
  • 3. If no such catch block exists, the program terminates.

The throw statement accepts a single argument, which is an object of the Exception class.

Syntax
//Syntax –
throw ThrowableObj

You can use the following code to throw the IllegalStateException exception :

CODE/PROGRAM/EXAMPLE
class demo
{
static void tdemo()
{
try
{
throw new IllegalStateException ();
}
catch (NullPointerException e)
{
System.out.println ("Not Caught by the catch block inside tdemo
().");
}
}
public static void main (String args[ ])
{
try
{
tdemo();
}
catch(IllegalStateException e)
{
System.out.println("Exception Caught in:"+e);
}
}
}

// O/P : C:\>javac demo.java
C:\>java demo
Exception Caught in:java.lang.IllegalStateException
C:\>

Using the throws Statement :

The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method.

This is done using the throws statement. The throws clause lists the types of exceptions that a method might throw.

Syntax
//Syntax –
[< access specifier >] [< modifier >] < return type > < method name
> [< arg list >] [ throws <exception list >]
CODE/PROGRAM/EXAMPLE
//Example:
You can use the following code to use the throws statement:
class demo
{
static void throwMethod ( ) throws ClassNotFoundException
{
System.out.println ("In throwMethod ");
throw new ClassNotFoundException ( );
}
public static void main (String args [ ])
{
try
{
throwMethod ( );
}
catch ( ClassNotFoundException e)
{
System.out.println (" throwMethod has thrown an Exception :" +e);
}
}
}
Output
C:\>javac demo.java
C:\>java demo
In throwMethod
throw Method has thrown an Exception :java.lang.Class Not Found
Exception

Creating and Using Your Own Exception Classes :

You can create your own exception class by extending an existing exception class

Syntax
//Syntax –
[modifiers] New Exception Class Name extends
ExceptionClassName
{
create constructors that usually delegate to super-constructors
}

You could then add any fields or methods that you wish, although often that is not required. You must, however, override any constructors you wish to use: Exception ( ), Exception(String message), Exception(String message, Throwable cause), Exception (Throwable cause). Usually you can just call the equivalent super-constructor. If you extend RuntimeException or one of its subclasses, your exception will be treated as a runtime exception.

When a situation arises for which you would like to throw the exception, use the throw keyword with a new object from your exception class, for example:

Syntax
//Syntax –
throw new ExceptionClassName(messageString);
#exception_handling_in_java_language #exception_handling_in_java #Compile_time_errors_in_java #Run_time_errors_in_java #try…catch_in_java #Finally_Block_in_java #Throwing_an_Exception_in_java

(New page will open, for Comment)

Not yet commented...