EXCEPTION HANDLING

Error:

Error is an abnormal condition whenever it occurs execution of the program will be stopped. In java language errors are classified into two types.
1.Compile time errors
2.Runtime Errors

Compile time errors:

These are the errors generated at compile time because of breakdown the rules of a programming language.
Ex: Missing semicolon at the ending of a statement, writing keywords in upper case etc..
Note: Compile time errors are also known as syntax errors.

Runtime errors:

These are the errors generated at the time of running of a program and these are raised because of writing wrong logic or because of providing wrong input values. Runtime errors are also known as aExceptions.
Example: Divide by Zero Exception, Array Indexoutofrange exception etc..
In the realtime application development it is very necessary to identify to solve either runtime exception or compile time error to get efficient output.
Compile time errors can be identified and solved by the developers, but runtime errors may be generated or raised to the enduser at the time of running of an application.
Whenever runtime error is generated JVM raises system defined error message, that may not understandable by the en user so that as a java developer this is our responsibility to convert system define error message to user friendly error message for better understanding or identification purpose ,in java language it can be possible using exception handling.

Definition of Exception Handling:

Exception handling is a special mechanism use to convert system defined error messages onto user friendly error messages. In java language exception handling can be achieved using try-catch construction.

Types of exceptions:

In java language exception are classified into following types.

Types of exceptions

Exception:

Exception is runtime error whenever it occur execution of the program will be stopped.

Predefined exception:

These are the exception already designed by the sunmicrosystem and these are raised commonlyfor every java developer.
Note: Predefined Exceptions are existing as predefined classes in java.lang package.

User defined Exception:

These are the exception designed by the user and these can be raised commonly for specific developer.

Asynchronous Exception:

These are the exceptions raised because of hardware failures, developer can’t be handle these type of exceptions explicitly. JVM handle asynchronous exception automatically using predefined classes called error.

Synchronous Exception:

These are the exceptions raised because writing wrong logic of because of providing wrong input values,these exceptions can be handle by both JVM and developer using exception class.

Checked Exception:

This is an exception verified at compile timebut raised at run time,for raising these exception which will be check secondary memory device harddisk.

Unchecked Exception:

This is an exception both verified and raised at runtime ,to raise these exception which will never check any secondary memory.

Hierarchy of predefined exception:

Following predefined classes are will raise different system defined error messages as a java developer we must convert these messages into user-friendly messages with help of exception handling mechanism.
Throwable is a predefined class used to handle all type of exceptions and this is super class for both error and exception class.
Hierarchy of predefined exception Class not found exception:
This is a predefined exception class raised whenever given class is not found at specific location.
File not found exception:
This is a predefined exception class raised whenever given file is not found at specific location.
IOException:
This is a predefined exception class raises while performing operation either writing or reading on a file.
InterruptedException:
It is a pre defined exception class, it raisedwhen ever thread disturbed while execution.
ArthmeticException:
It is a pre defined exception class, it raises if any problem it occurs while performing mathematical operations.
ArrayIndexOutOfBoundException:
It will rise when ever data is accessing from this array with the out of index value.
StringIndexOutOfBoundException:
It will rise whenever string index is out of range.
NullPointerException:
Which will raise while accessing any data with the null reference.
NumberFormatException:
Which will raise whenever we are trying to store the data in the illegal data type
Ex: Storing string value into integer data type.
NoSuchMethodException:
If the specified method methodname is not existing in the program while accessing the above exception is raised.
NOSuchFieldException:
Which will rise if the specified variables are not existing in the program while accessing.

Tracking of exception:

Whenever we are providing wrong input values or writing wrong logics there may be a chance of raising exceptions and that can be track and handled shown below.

Tracking of exception

Try-catch construction:

in java language exception handling can be achieved using try-catch block construction. Try and catch blocks are the keywords in the java language, it is used to convert system defined error messages into user friendly error messages very efficiently.
Try block always contains logic of the program or problematic code, catch block contains user friendly error messages.

Try-catch construction
1. One try block can have many number of exception statements , but it raises only one exception at a time.
2. One catch block can handle only one exception at a time.
3. For one try block multiple catch blocks are exists.
4. Without try block no catch block can exist.
5. Without catch block try block can exist if it is containing finally block otherwise it is not possible.
6. The statements of try block are executed whenever program is executed but the statements of catch block are executed whenever exception is raised.
7. Once control comes out of the try block control will never return back to same block to execute the statements.
Operations of try block:
Whenever program statements running, control enter into try block and it executes all the statements and gives output if no exception is raised.
Note: In this scenario catch block will not be executed.
While executing statements of try block, if any exception is raised JVM throws the exception to the related exception class object. Immediately it will be raised by the same try block and immediately the first catch block will check whether raised object is matching with exception class of it. If it is matching the statements are executed, otherwise another catch block will be verified, this process will continue until the last catch block.
Note: if any exception is raised in the try block it starts verification in the first catch block onwards.
Note: try catch construction always should be inside a method only.

Write a program to handled the arithmetic exception

importjava.util.*;
class Arithmetic
{
public static void main(String args[])
{
intx,y,z;
System.out.println("enter x,y values");
Scanner s=new Scanner (System.in);
x=s.nextInt();
y=s.nextInt();
try
{
z=x/y;
System.out.println("division of two number is"+z);
}
catch(ArithmeticException e)
{
System.out.println("Denominator should not be zero");
}
}
}
Output:
javacArithmetic.java
java Arithmetic
Enter x, y values
12
2
division of two number is:6

java Arithmetic
Enter x, y values
12
0
Denominator should not be zero

Write a program to handle try with multiple catch blocks

importjava.util.*;
class Arithmetic
{
public static void main(String args[])
{
int x,y,z;
System.out.println("Enter x,y values");
Scanner s=new Scanner (System.in);
x=s.nextInt();
y=s.nextInt();
try
{
z=x/y;
System.out.println("division of two number is"+z);
}
catch(ArithmeticException e)
{
System.out.println("Denominator should not be zero");
}
catch(ArrayIndexOutofBoundException ee)
{
System.out.println("your index is out of range");
}
}
}

Write a program to handle multiple exception try catch blocks.

class A
{
void f1()
{
System.out.println("hello");
}
}

classMuldemo
{
static Aoa;
public static void main(String args[])
{
try
{
oa.f1();
}
catch(NullPointerException ne)
{
System.out.println("no memory is pointed to object reference");
}
try
{
String s="student";
char c=s.charAt(30);
System.out.println("c="+c);
}
catch(StringIndexOutOfBoundsException se)
{
System.out.println("String index is out of bounds");
}
}
}

Output:
C:\Documents and Settings\sateesh\Desktop>javac Muldemo.java
C:\Documents and Settings\sateesh\Desktop>java Muldemo
no memory is pointed to object reference
String index is out of bounds

A java program can contain multiple try –catch block to handle multiple exceptions at a time.
A java program can contain multiple try –catch block to handle  multiple exceptions at a time
If any try-catch block is existing another try or catch block is known as nested try-catch .this is an alternative approach to handle multiple exceptions at a time .but this is not recommended in real time applications because it is irreliableor insufficient handling if exception.
A java program can contain multiple try –catch block to handle  multiple exceptions at a time

Handling of unknown Exception:

If any developer don’t have any idea about any existing exception (like exception name, exception message etc) is known as unknown exception.
In java language unknown exception can be handle in three different ways.

1. Using Exception class
2. Using printStackTrace method()
3. Using getMessage method()

Using Exception class:

Exception is a super class fro all types of checked and unchecked exceptions classes .so that details of any exception can be known with help of exception class object.
try
{
-----
-----
}
catch(Exception objref)
{
System.out.error(objref);
}
Exception class object displays two properties of given exception
1. Name of the exception
2. Exception message
Based on above details developer should rewrite code with the exception class name and should provide user friendly error message.

Write a java program to know above exception details using exception class.

class ExceptionDemo
{
public static void main(String args[])
{
intx,y,z;
try
{
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("z="+z);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
Output:
C:\Documents and Settings\sateesh\Desktop>java Except 12 sa
java.lang.NumberFormatException: For input string: "sa"

Using printStackTrace():

It is a predefined method of Throwable class used to display three details of exception
1. Name of exception
2. Exception class
3. Line number


class ExceptionTrace
{
public static void main(String args[])
{
intx,y,z;
try
{
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("z="+z);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output:
C:\Documents and Settings\sateesh\Desktop>java Except 12 sa
java.lang.NumberFormatException: For input string: "sa"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
atjava.lang.Integer.parseInt(Integer.java:449)
atjava.lang.Integer.parseInt(Integer.java:499)
atExcept.main(Except.java:9)

Inthe above example printStackTrace method can be called either by using Throwable class object or by using it’s derived class object like exception class.

Using getMessage():

It is a predefined method in Throwable class with returns only exception messages
class ExceptionMessage
{
public static void main(String args[])
{
intx,y,z;
try
{
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("z="+z);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Output:
C:\Documents and Settings\sateesh\Desktop>java Except 12 sa
For input string: "sa"

Note:
By using any of above three mechanism java developer can find the details about unknown exception and he has to rewrite the code by providing proper exception class name user friendly error messages.
In realtime application it is highly recommended to write multiple blocks for single try block and at last we must common exception handler block.

Syntax:
try
{
----
----
catch(ArithmeticException ae)
{ // these are individual exception handlers
---
---
}
catch(nullPointerException ne)
{
---
---
}
catch(Exception e)
{
Ssytem.out.prinln(e); // this is common exception handler
}

Note: While writing try-catch construction common exception handler should as a last catch block otherwise it gives error.

Throws:

Throws is a keyword in java language can be used to throws an exception which is raised in the method body to its calling method.
Throws keyword always should be followed by method signature.
Syntax:
returntype methodname (lp/np) throws Exception class1,exception class2…
{
// problematic code
-----
-----
}

Many number of exception classes can be followed by throws keyword.while using throws keyword it is mandatory to keep the calling method with in try block and that should be handle using appropriate catch block.
try
{
obj.methodname();
----
----
}
catch(Exception obj)
{
-----
-----
}
The main advantage with throws keyword is multiple exceptions raised in multiple methods of multiple classes can be handle by writing single try-catch construction.

class Demo
{
void f1() throws ArrayIndexOutOfBoundsException,StringIndexOutOfBoundsException
{
String v="hello";
char c=v.charAt(0);
int a[]=new int[5];
a[15]=20; \\ correct statement is a[1]=20;
System.out.println("a[15]="+a[15]); //correct statement is System.out.println("a[1]="+a[1]);
}
void f2() throws ArithmeticException
{
int x=10,y=0,z;// correct statement is int x=10,y=2,z;
z=x/y;
System.out.println("z="+z);
}
}
class Demo1
{
void f4(String s1,String s2) throws Exception
{
int f1=Integer.parseInt(s1);
int f2=Integer.parseInt(s2);
int f3=f1+f2;
System.out.println("f3="+f3);
}
}
class ExceptionThrows
{
public static void main(String args[])
{
Demo d=new Demo();
Demo1 dm=new Demo1();
try
{
d.f1();
d.f2();
dm.f4("ten","20"); \\correct statement is dm.f4("10","20");
}
catch(StringIndexOutOfBoundsException se)
{
System.out.println("String index is outof range");
}
catch(ArrayIndexOutOfBoundsExceptionee)
{
System.out.println("array index is outof range");
}
catch(ArithmeticException ae)
{
System.out.println("Denominator should not be zero");
}
catch(NumberFormatExceptionee)
{
System.out.println("please enter integer values only");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:
C:\Documents and Settings\sateesh\Desktop>java ExceptionThrows
a[15]=20
String index is outof range

Rethrowing of exception:

Whenever same exception is thrown to multiple locations or it same exception is throwing to another location is known as rethrowing.
Ex:
class Demo
{ public static void main(String args[])throws IOException
{
InputStream is=new InputStream(-----);
is.read(----); //raise to exception
}

In the above example read method is existing in input stream class as a predefined method and that is followed by throws IOException that means the method will throws IOException to the calling method and same exception is throws to JVM for handling is called rethrowing of exception.

Finally block:

It is a keyword in java language ,it is collection of statements existed in the form of block finally block. Finally block contains the statements of try block which are existing mandatary irrespective raising exception (Either exception is raised or not raised);
Sntax: finally
{
Set of excitable statements of try block
}

class Finally
{
public static void main(String args[])
{
int x=10,y=0,z;
try
{
z=x/y;
System.out.println("Z="+z);
//System.out.println("hello");
}
catch(ArithmeticException ae)
{
System.out.println("denominator should not be zero");
}
finally
{
System.out.println("hello");// try block statement
} System.out.println("welcome to Java class");//normal program statemet
}
}

Output:
C:\Documents and Settings\sateesh\Desktop>java Finally
denominator should not be zero
hello
welcome to Java class
In the above example either exception is raised or not raised the statements of finally block executed .
Note:
the statements whatever is executing with in finally block these are generally try block statements.

User defined exception:

If any exception is designed by the user and it if used commonly by specific number of developers is known as user defined exception.
If any exception is unable to handle by the JVM then those type of exceptions can be handled by the user by creating separate execution block.
Rules to design user defined exception:
1. Create a package with valid user defined name.
2. Create a public class under given package with valid user defined name.
3. Extends either runtime exception or exception class to the user defined class.
4. Create a public constructor with string parameter.
4. Call the super class constructor with a derived class constructor.
5. Save the program with exception class name.java
Syntax
package PackageName
public class ClassName extends Exception
{
publicclassname(String variablename)
{ super(String variable);
}
}
In the above example (Syntax) String variable can be used to common exception message and main aim of creation of user defined exception class is to package the exception message commonly to all it’s super class.

Write a program to handle negative age exception.

// Save the program Nage.java
package studentage;
public class Nage extends Exception
{
public Nage(String s)
{
super(s);
}
};

Save the program Verify.java

package verifyage;
import studentage.Nage;
public class Verify
{
public void checkage(int a) throws Nage
{
if(a>0)
{
System.out.print("valid age");
}
else
{
Nage n=new Nage("Invalid age");
throw(n);
}
}
}

StudentDemo.java

import studentage.Nage;
import verifyage.Verify;
import java.util.Scanner;
class StudentDemo
{
public static void main(String args[])
{
System.out.print("Enter your age");
Scanner s=new Scanner(System.in);
int ag=s.nextInt();
Verify v=new Verify();
try
{
v.checkage(ag);
System.out.print("your age is "+ag);
}
catch(Nage ne)
{
System.out.println("Age should not be Nagetive");
}
}
}
Output:
Enter your age:20
Valid age
Enter your age :-20
Age should not be negative.


Throws is a keyword used to forward the exception to the method col whereas throw is a keyword used to throw exception to the method sign.
Throws always should be followed by method signature whereas throw keyword always should exist within method only.

Write a program to handle negative salary exception.

//Save the program with Nsal.java package empsalary;
public class Nsal extends Exception
{
publicNsal(String s)
{
super(s);
}
}

//Save the program with Verify.java
package verifysal;
import empsalary.Nsal;
public class Verify
{
public void checksal(int a) throws Nsal
{
if(a>0)
{
System.out.print("Valid salary");
}
else
{
Nsal n=new Nsal("Invalid salary");
throw(n);
}
}
}

// Save the program with Salary.java
import empsalary.Nsal;
import verifysal.Verify;
importjava.util.Scanner;
class Salary
{
public static void main(String args[])
{
System.out.print("Enter your salary");
Scanner s=new Scanner(System.in);
intsl=s.nextInt();
Verify v=new Verify();
try
{
v.checksal(sl);
System.out.print("your salary is "+sl);
}
catch(Nsal ne)
{
System.out.println("salary should not be Nagetive");
}
}
}
Output:
Enter your salary:20000
Valid age
Enter your age :-20000
salary should not be negative.