Exception Handling

Handling Error/Exceptions
Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional events requiring special processing – often changing the normal flow of program execution. It is provided by specialized programming language constructs or computer hardware mechanisms.
In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information. For example, a floating point divide by zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be resolvable transparently.
An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
* A user has entered invalid data.
* A file that needs to be opened cannot be found.
* A network connection has been lost in the middle of communications or the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of exceptions: -
1. Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
2. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
3. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Exception Hierarchy:: -
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.

Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available.
Java defines several other types of exceptions that relate to its various class libraries.
Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked
Following is the list of Java Unchecked RuntimeException.
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
Following is the list of Java Checked Exceptions Defined in java.lang.
Exception Description
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

Exceptions Methods:: -
Medthods available in the Throwable class: -
SN Methods with Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Should we make our exceptions checked or unchecked?
f a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception
Exception keywords
In any programming language , if we give any invalid input then we get System error messages , which is not recommended To convert System error messages into user friendly messages , it is highly recommended to use Exception handling . Exception Handling contains 5 keywords
1. try
2. catch
3. finally
4. throws
5. throw
Syntax :
try {
statements;
} catch (exceptionType1 identifier1) { // one or multiple
statements;
} catch (exceptionType2 identifier2) {
statements;
}
...
} finally { // one or none
statements;
}
try block:
1. This is one of the block in which we write the block of statements which causes problems at run time
2. Whenever an exception happens in try block ,program exception is abnormally terminated and control goes to appropriate catch block
3. After executing catch block , control never comes to try block to execute rest of statements
. 4. Each and every try block must contain atleast one catch block
5. One try block can contain another try block
Catch block:
1. This is the block in which we write the block of statements which proovides user Friendly Exceptions
2. If no exeception is thrown by any of the methods called or statements executed inside the try-block, the catch-block is simply ignored. It will not be executed.
3. At any point only one catch block will execute
4. In catch block as a java programmer we declare an object of appropriate Exception and automatically jvm will reference an object of appropriate Exception provided an exception has taken place.
5. highly recommended to write multiple catch blocks
Finally block :
1. Writing Finally block is optional
2. In this block we write block of statements which will relinquish (close ,release ) the resources (files ) which are obtained in try block
2. Finally block is executed compulsorily
1. try : - Defines a block of statements that have exception handling. If an exception is thrown inside the try block, an optional catch block can handle declared exception types. Also, an optional finally block can be declared that will be executed when execution exits the try block and catch clauses, regardless of whether an exception is thrown or not. A try block must have at least one catch clause or a finally block..
2. catch: - Defines an exception handler—a group of statements that are executed if an exception is thrown in the block defined by a preceding try keyword. The code is executed only if the class of the thrown exception is assignment compatible with the exception class declared by the catch clause.
3. finally: - Used to define a block of statements for a block defined previously by the try keyword. The finally block is executed after execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught, or execution left method in the middle of the try or catch blocks using the return keyword.
4. throws: - Used in method declarations to specify which exceptions are not handled within the method but rather passed to the next higher level of the program. All uncaught exceptions in a method that are not instances of RuntimeException must be declared using the throws keyword.
5. throw: - Causes the declared exception instance to be thrown. This causes execution to continue with the first enclosing exception handler declared by the catch keyword to handle an assignment compatible exception type. If no such exception handler is found in the current method, then the method returns and the process is repeated in the calling method. If no exception handler is found in any method call on the stack, then the exception is passed to the thread's uncaught exception handler.
Example 1: - Exceptions can be handled by using 'try-catch' block. Try block contains the code which is under observation for exceptions. The catch block contains the remedy for the exception. If any exception occurs in the try block then the control jumps to catch block.
class exceptions
{
public static void main(String Args[])
{
int[] array = new int[3];
try{
for(int i=0;i<4;++i)
{
array[i] = i;
}
System.out.println(array);
}
catch(ArrayIndexOutOfBoundsException e){
//printed just to inform that we have entered the catch block
System.out.println("Oops, we went to far, better go back to 0!");
}
finally{
System.out.println(array);
//method call to continue program
}
}
}
Output: -
C:\java>javac exception.java
C:\java>java exceptions
Oops, we went to far, better go back to 0!
[I@3e25a5
Example 2: - Using Throw Excetpion in Java
* The 'throws' clause in java programming language is belongs to a method to specify that the method raises particular type of exception while being executed.
* The 'throws' clause takes arguments as a list of the objects of type 'Throwables' class.
* Anybody calling a method with a throws clause is needed to be enclosed within the try catch blocks.
class MyExplicitThrow {
public static void main(String a[]){
try{
MyExplicitThrow met = new MyExplicitThrow();
System.out.println("length of JUNK is "+met.getStringSize("JUNK"));
System.out.println("length of WRONG is "+met.getStringSize("WRONG"));
System.out.println("length of null string is "+met.getStringSize(null));
} catch (Exception ex){
System.out.println("Exception message: "+ex.getMessage());
}
}
public int getStringSize(String str) throws Exception{
if(str == null){
throw new Exception("String input is null");
}
return str.length();
}
}
Output: -
C:\java>javac exception.java
C:\java>java MyExplicitThrow
length of JUNK is 4
length of WRONG is 5
Exception message: String input is null
Example 3: - Using Final keyword in Java
* The finally block always executes immediately after try-catch block exits.
* The finally block is executed incase even if an unexpected exception occurs.
* The main usage of finally block is to do clean up job. Keeping cleanup code in a finally block is always a good practice, even when no exceptions are occured.
* The runtime system always executes the code within the finally block regardless of what happens in the try block. So it is the ideal place to keep cleanup code.
class MyFinallyBlock {
public static void main(String[] a){
/**
* Exception will occur here, after catch block
* the contol will goto finally block.
*/
try{
int i = 10/0;
} catch(Exception ex){
System.out.println("Inside 1st catch Block");
} finally {
System.out.println("Inside 1st finally block");
}
/**
* In this case exception won't, after executing try block
* the contol will goto finally block.
*/
try{
int i = 10/10;
} catch(Exception ex){
System.out.println("Inside 2nd catch Block");
} finally {
System.out.println("Inside 2nd finally block");
}
}
}
C:\java>javac exception.java
C:\java>java MyFinallyBlock
Inside 1st catch Block
Inside 1st finally block
Inside 2nd finally block
Example 4: - Multiple catch blocks
* A single try block can have multiple catch blocks. This is required when the try block has statements that generates different types of exceptions.
* If the first catch block contains the Exception class object then the subsequent catch blocks are never executed.
* The last catch block in multiple catch blocks must contain the Exception class object. This is because, the java complier gives an error saying that the subsequent catch blocks haven't been reached. This is known as Unreachable code problem.
import java.net.MalformedURLException;
import java.net.URL;
class MyMultipleCatchBlocks {
public static void main(String a[]){
MyMultipleCatchBlocks mmcb = new MyMultipleCatchBlocks();
mmcb.execute(1);
mmcb.execute(2);
}
public void execute(int i){
try{
if(i == 1){
getIntValue("Java Exception");
} else {
getUrlObj("anuj32.net46.net/desktop/");
}
} catch (NumberFormatException nfe){
System.out.println("Inside NumberFormatException... "+nfe.getMessage());
} catch (MalformedURLException mue){
System.out.println("Inside MalformedURLException... "+mue.getMessage());
} catch (Exception ex){
System.out.println("Inside Exception... "+ex.getMessage());
}
}
public int getIntValue(String num){
return Integer.parseInt(num);
}
public URL getUrlObj(String urlStr) throws MalformedURLException{
return new URL(urlStr);
}
}
C:\java>javac exception.java
C:\java>java MyMultipleCatchBlocks
Inside NumberFormatException... For input string: "Java Exception"
Inside MalformedURLException... no protocol: anuj32.net46.net/desktop/
C:\java>javac exception.java
C:\java>java MyMultipleCatchBlocks
Inside NumberFormatException... For input string: "Java Exception"
Inside MalformedURLException... no protocol: anuj32.net46.net/desktop/
Example 5: - How to create custom exception in Java
Sometimes it is required to develop meaningful exceptions based on application requirements. We can create our own exceptions by extending 'Exception' class. Below example shows how to create custom exception by extending Exception class.
class MyOwnException {
public static void main(String[] a){
try{
MyOwnException.myTest(null);
} catch(MyAppException mae){
System.out.println("Inside catch block: "+mae.getMessage());
}
}
static void myTest(String str) throws MyAppException{
if(str == null){
throw new MyAppException("String val is null");
}
}
}
class MyAppException extends Exception {
private String message = null;
public MyAppException() {
super();
}
public MyAppException(String message) {
super(message);
this.message = message;
}
public MyAppException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
Output: -
C:\java>javac exception.java
C:\java>java MyOwnException
Inside catch block: String val is null


Free Web Hosting