Exception Handling in Java

An exception condition is a problem that prevents the continuation of the current method or scope. With an exceptional condition, you cannot continue processing because you do not have the information necessary to deal with the problem in the current context. All you can do is jump out of the current context and relegate that problem to a higher context.  Exceptions are thus abnormal situations / unexpected events that occur during the execution of a program. An exception might result due to an unavailable resource, unexpected input from a user, or simply a logical error on the part of the programmer.

Exceptions - Systemic internal flow underneath:



1. Whenever, we pass irrelevant input to a java program, Java virtual machine (JVM) cannot process the irrelevant input. 
2. JVM contacts to Java Run Time Environment (JRE) for getting an appropriate exception class
3. JRE contacts to java.lan.throwable to learn the type of exception that got encountered
4. Java.lan.throwable decides what type of exception it is. And process the message to JRE
5. JRE pass the type of exception to JAVA API.
6. Java API will find appropriate sub classs exceptions depending on the type of exception (i.e. java.lang.exception, java.RuntimeException or Java.lang.error)
7. Java API will send sub class exception to JRE
8. JRE will in turn pass the appropriate sub class exception to JVM
9. JVM will create an object of appropriate exception class which generates System Error Messages
10. In order to make the program robust, we have to convert System Error Messages to User-friendly Error messages by using Exception handler.
11. Java programmer handles the exception through converting the same into user friendly error messages.

Hierarchy of Java Exception classes

Java defines a rich inheritance hierarchy of all objects that are deemed Throwable. Please find small portion of the hierarchy in below figure. The hierarchy is intentionally divided into two subclasses: Error and Exception. Errors are typically thrown only by the Java Virtual Machine and designate the most serious situations that are unlikely to be recoverable, such as when the virtual machine is asked to execute a corrupt class file, or when the system runs out of memory. In contrast, exceptions designate situations in which a running program might reasonably be able to recover, for example, when unable to open a data file.


Types of Exceptions:

1. Pre-defined exceptions are those that are developed by Oracle and supplied as a part of JDK to deal with universal problems.

(1.1) Synchronous exceptions : Programmatic errors. The super class for this is "java.lang.Exceptions" for all synchronous exceptions.

(1.1.1) Checked Exceptions: Results during Compiling time. Super class for this is "java.lang.Exception"
(1.1.2) Unchecked exceptions: Results during Run Time. Super class for this is "java.lang.RuntimeExceptions"

(1.2) Asynchronous exceptions : Deals with Hardware problems. The class "java.lang.Error" is the super class for all the asynchronous exceptions. Examples for Asynchronous exceptions are Power failure, stackoverflow errorHard disk crash etc.

2. User defined exceptions / Business flow exceptions are those that are developed by Java Programs as a part of Application development for dealing with specific problmes. 

Exception Handling in Java:

The general methodology for handling exceptions is a try-catch construct in which a guarded fragment of code that might throw an exception is executed. If it throws an exception, then that exception is caught by having the flow of control jump to a predefined catch block that contains the code to analyze the exception and apply an appropriate resolution. If no exception occurs in the guarded code, all catch blocks are ignored.
A typical syntax for a try-catch statement in Java is as follows:

try
{

//Guarded code that may throw exception 

// (1) Java try block is used to enclose the code that might throw an exception. It must be used within the method.

// (2) Java try block must be followed by either catch or finally block.
// (3) Incase of any exception, execution will get terminated and rest of the statements in try block will not be executed at all. The control jumps automatically to appropriate "catch block".
// (4) Each and every try {} must be immediately followed by catch{}. That means, no intermediate statements are allowed between try {} and catch {} block
// (5) For every try {} block, we must have atleast one catch{} block. It is highly recommended to write n number of catch blocks for n number of problematic statements. 
}

catch (exceptionType1, variable1)
{
// remedy body1
// (1) Catch block helps to catch system error message and convert the same to user friendly messages using remedy block of statements
// (2) catch block will be executed only if any exception error occurs in the try {} block.

// (3) At a time only one Exception is occured and at a time only one catch block is executed.
// (4) All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .

}

catch (exceptionType2, variable2)
{
// remedy body2
}

finally
{
//(1) Java finally block is a block that is used to execute important code such as closing connection, stream etc.
//(2) Java finally block is always executed whether exception is handled or not.
//(3) Java finally block must be followed by try or catch block.
//(4) Writing the finally block is optional.
//(5) For each try block there can be zero or more catch blocks, but only one finally block.

//(6) The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
}

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.

Syntax of java throws:

return_type method_name() throws exception_class_name
{  
//method code  
}  

Java throw exception

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. 

The syntax of java throw keyword is given below

throw exception;  

(1) A Programmer can raise an exception programatically by using throw key word. It is part of method body.
(2) If we write throw keyword, writing throws keyword is mandatory. 

Common Scenarios where Exceptions may Occur:


(1) ArithmeticException: If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException  

(2) NullPointerException: If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

String s=null;  
System.out.println(s.length());//NullPointerException  

(3) NumberFormatException: Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.

String s="abc";  
int i=Integer.parseInt(s);//NumberFormatException  

(4) ArrayIndexOutOfBoundsException: If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException

int a[]=new int[5];  
a[10]=50; //ArrayIndexOutOfBoundsException