• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

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.
Example:
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 Exceptions.
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. exception

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. hierachi

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. tracingexception

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.
Syntax:

try
{
Logic of the code
}
catch(NameOfTheExcepton object)
{
User Friendly Message
}
catch(NameOfTheExcepton object)
{
User Friendly Message
}
..
..



Rules To Create A try-catch Block
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.


A java program can contain multiple try –catch block to handle multiple Exceptions at a time. multiple exceptions

Nested try-catch
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.
Nested try-catch

Write a program to handle try with single catch block

Write a program to handled the Arithmetic Exception

import java.util.*;
class Main
{
public static void main(String args[])
{
int x,y,z;
System.out.println("Enter x,y values");
Scanner s=new Scanner (System.in);
try
{
x=s.nextInt();
y=s.nextInt();
z=x/y;
System.out.println("Division Of Two Number Is "+z);
}
catch(ArithmeticException e)
{
System.out.println("Denominator should not be zero");
}
}
}


Output:
Enter x,y values
10
2
Division Of Two Number Is 5


Enter x,y values
10
0
Denominator should not be zero
Write a program to handle try with Multiple catch blocks

Write a program to handled the Arithmetic Exception

import java.util.*;
class Main
{
public static void main(String args[])
{
int x,y,z;
System.out.println("Enter x,y values");
Scanner s=new Scanner (System.in);
try
{
x=s.nextInt();
y=s.nextInt();
z=x/y;
System.out.println("Division Of Two Number Is "+z);
}
catch(ArithmeticException e)
{
System.out.println("Denominator should not be zero");
}
catch(InputMismatchException ee)
{
System.out.println("Please Enter Numbers Only");
}
}
}


Output:
Enter x,y values
10
2
Division Of Two Number Is 5


Enter x,y values
10
0
Denominator should not be zero

Handling of Unknown Exceptions:
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 for all types of checked and unchecked exceptions classes .so that details of any exception can be known with help of exception class object.

Syntax:

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.

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

class Main
{
public static void main(String args[])
{
int x,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:
Compile: javac Main.java
Run: java Main 12 sa
java.lang.NumberFormatException: For input string: "sa"

Above output:
1.Name of the Exception: java.lang.NumberFormatException:
2.Exception message : 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 Message
3.Line number

Write a java program to know above exception details using printStackTrace() Method.

class Main
{
public static void main(String args[])
{
int x,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:
Compile: javac Main.java
Run: java Main 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.
Above output:
1.Name of the Exception: java.lang.NumberFormatException:
2.Exception message : For input string: "sa"
3.Line Number: 48,449,9
Using getMessage():
It is a predefined method in Throwable class with returns only exception messages

1.Exception message

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(NumberFormatException ne)
{
--
--
}
catch(Exception e)
{
System.out.prinln(e); // this is common exception handler
}

Write a java program to know above exception details using getMessage Method.

class Main
{
public static void main(String args[])
{
int x,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:
Compile: javac Main.java
Run: java Main 12 sa
For input string: "sa"
Throws Keyword:
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 Exceptionclass1,...
{
--
--
}


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 A
{
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 B
{
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 Main
{
public static void main(String args[])
{
A a=new A();
B b=new B();
try
{
a.f1();
a.f2();
b.f4("ten","20"); \\correct statement is dm.f4("10","20");
}
catch(StringIndexOutOfBoundsException se)
{
System.out.println("String index is outof range");
}
catch(ArrayIndexOutOfBoundsException ee)
{
System.out.println("array index is outof range");
}
catch(ArithmeticException ae)
{
System.out.println("Denominator should not be zero");
}
catch(NumberFormatException ee)
{
System.out.println("please enter integer values only");
}
catch(Exception e)
{
System.out.println(e);
}
}
}


Rethrowing of Exception:
Whenever same exception is thrown to multiple locations or it same exception is throwing to another location is known as rethrowing.
Example:

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).
Syntax:

finally
{
Set of excitable statements of try block
}

class Main
{
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
}
}
}

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.
5.Call the super class constructor with a derived class constructor.
6.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
1.Exception Creation Program
package studentage;
public class Nage extends Exception
{
public Nage(String s)
{
super(s);
}
};

Save the program Verify.java

2.Exception verification Program
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

3.Main Program
import studentage.Nage;
import verifyage.Verify;
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
System.out.print("Enter your age"); Scanner s=new Scanner(System.in);
int a=s.nextInt();
Verify v=new Verify();
try
{
v.checkage(a);
System.out.print("your age is "+a);
}
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.

What is difference between the throws and throw ?
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.