Exception Handling
In JAVA
-M Vishnuvardhan,
Dept. of Computer Science,
SSBN Degree College, ATP
SSBN Degree College, ATP M Vishnuvardhan
Introduction
In general a program contains the
following types of errors
a)Compile-Time Errors
b)Run-Time Errors
SSBN Degree College, ATP M Vishnuvardhan
Compile-Time Errors
Compile time errors are mainly due to the following reasons
a)Misspelt of the keywords i.e., float x,y;
b)Wrong Identifier names i.e., int avg?marks;
c)Wrong Syntax i.e., missing of semicolon …
d)Wrong semantics i.e., int x=3.14;
These errors are identified by the compiler and can be rectified very
easily
SSBN Degree College, ATP M Vishnuvardhan
Run-Time Errors
In programs there are certain types of errors which are not
found at compilation time. These are known at the time of
running. The compiler cant find these category of errors.
Run-time errors are mainly due to the wrong input and wrong
logic in the program. Run-time errors are called as Exceptions.
E.g., int a,b,c;
a= 20; b=0;
c= a/b;
SSBN Degree College, ATP M Vishnuvardhan
Exception - Defined
An desirable/ abnormal situation which prevail inside the
program is called as an Exception.
In general when ever exception occurs the program suddenly
stops. This leads to a major problem when working with files,
databases, network connections….
Exception handling is a technique or mechanism of handling
seriousness of the exception.
Traditional programming languages lack of exception handling
mechanism. But all modern programming languages are capable
of handling the exception
Robust programming language
SSBN Degree College, ATP M Vishnuvardhan
Exceptions in java
The undesirable condition in java are categorized in to two types
1.Error – Hardware related can’t be handled from the program
2.Exception – Software related can be handled from the program
Object
Throwable
Error Exception
StackOver
FlowError
Virtual
MachineError
Checked
Exception
Unchecked
Exception
UserDefined
Exception
SSBN Degree College, ATP M Vishnuvardhan
Categories of Exceptions
Exception is the base class of all types of the Exceptions
Checked Exception:- Must be handled by the programmer other wise
compile time error is generated
Unchecked Exception:- It may or may not be handled by the programmer
no compile time error is generated. RunTimeException is the base class of
all unchecked Exceptions
User Defined Exceptions:- In general java deals with common types of
exception for a specific type of exception. The programmer has to define
the exceptions of the specific type those are called as User-defined
Exceptions
SSBN Degree College, ATP M Vishnuvardhan
Checked Exceptions
Exception
FileNotFoundException
IllegalThreadStateException
InterruptedException
IOException
SQLException
SSBN Degree College, ATP M Vishnuvardhan
Checked Exceptions
FileNotFoundException:
Occurs when an attempt is made to open a file which is not
actually present.
IllegalThreadStateException:
Occurs when a thread is moved to an illegal state
InterruptedException:
Occurs when a Thread is interrupted.
IOException:
Occurs due to the failure of the h/w or s/w associated with
the I/O devices etc.,
SQLException:
Occurs when a database connection is not available or when it
returns null.
SSBN Degree College, ATP M Vishnuvardhan
RunTimeException
RunTimeException
ArithmeticException
NumberFormatException
NullPointerException
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
SSBN Degree College, ATP M Vishnuvardhan
Runtime Exceptions
ArithmeticException:
Occurs when a number is divided by zero
e.g.: int c=20/0; ---> ArithmeticException
NumberFormatException:
Occurs an attempt is made to convert String with invalid digits
to number
e.g.: String s="123abc";
int x= Integer.parseInt(s); -- > NumberFormatException
NumberFormatException:
Occurs when a reference is used with out instance
E.g.: Rectangle r1; //Object is not initialized.
r1.display();
SSBN Degree College, ATP M Vishnuvardhan
Runtime Exceptions
ArrayIndexOutOfBoundsException:
Occurs when an array is referred beyond the boundaries
e.g: int a[]={10,20,30,40,50};
System.out.println(a[20]); //referring the array beyond boundaries
ArrayStoreException:
Occurs when an attempt is made to store wrong type of object
is stored in array of objects.
Eg: String s[]=new String [5];
s[0]=new Integer(75); // storing integer object in String array
StringIndexOutOfBoundsException:
Occurs when a String is referred beyond the string boundaries.
e.g. String s=“Java Program”;
char ch =s.charAt(23); // referring String beyond the
boundaries
SSBN Degree College, ATP M Vishnuvardhan
Exception Handling in Java
Exception handling in java can be done with the help of keywords
like try, catch, finally, throw, throws
try
{
-------
-------
}
catch(ExceptionClass 1)
{ }
catch(ExceptionClass 2)
{ }
----
-----
-----
catch(ExceptionClass n)
{ }
finally
{ }
SSBN Degree College, ATP M Vishnuvardhan
Exception Class Methods
 String getMessage(): returns the message returns
associated with the Exception
 String toString(): prints the exception name as well as
the message associated with the exception
 void printStackTrace(): prints the exception name,
message associated with it, line number in which the
exception is present and the method name where the
statement is present and class where the method is
located i.e..., full details
SSBN Degree College, ATP M Vishnuvardhan
finally block
A try block may contain any number of catch blocks but it contains
at most one finally block. The finally block is executed at least
once whether the exception occurs or not in the try block.
In general the try hold the statements like closing of files, closing
of streams, closing of the database connection and network
connections.
SSBN Degree College, ATP M Vishnuvardhan
User defined Exceptions
Java deals the general type of the exceptions which commonly
occur in the program. For an application type or a specific type of
exception we need to create our own exceptions. These exception
are called as user defined exceptions
Steps to create User defined exception
Create a class by extending from Exception class
If needed override any one of the Exception class methods
Check the condition for occurring of the exception
Create and object for the Exception and manually throw it using
throw keyword
SSBN Degree College, ATP M Vishnuvardhan
throw keyword
throw:- It is used to throw and exception from the try block
towards the catch blocks manually. Most of the it is used with user
defined exceptions where exception must be manually throw from
try block.
Syntax : throw new ExceptionClassName(<<Params>>);
E.g.: throw new ArithmeticException();
SSBN Degree College, ATP M Vishnuvardhan
throws keyword
throws:- It is generally used to postpone the exception handling.
Generally used at the method declaration to list the exception
which occur in the method. Any one who uses the method must
and should handle the exception listed
E.g.: public void test () throws IOException
{
======
}
public static void main(String args[])
{
try
{
test()
----
}
catch(IOException e)
{
---
}
}
SSBN Degree College, ATP M Vishnuvardhan
Questions

Exception handling

  • 1.
    Exception Handling In JAVA -MVishnuvardhan, Dept. of Computer Science, SSBN Degree College, ATP
  • 2.
    SSBN Degree College,ATP M Vishnuvardhan Introduction In general a program contains the following types of errors a)Compile-Time Errors b)Run-Time Errors
  • 3.
    SSBN Degree College,ATP M Vishnuvardhan Compile-Time Errors Compile time errors are mainly due to the following reasons a)Misspelt of the keywords i.e., float x,y; b)Wrong Identifier names i.e., int avg?marks; c)Wrong Syntax i.e., missing of semicolon … d)Wrong semantics i.e., int x=3.14; These errors are identified by the compiler and can be rectified very easily
  • 4.
    SSBN Degree College,ATP M Vishnuvardhan Run-Time Errors In programs there are certain types of errors which are not found at compilation time. These are known at the time of running. The compiler cant find these category of errors. Run-time errors are mainly due to the wrong input and wrong logic in the program. Run-time errors are called as Exceptions. E.g., int a,b,c; a= 20; b=0; c= a/b;
  • 5.
    SSBN Degree College,ATP M Vishnuvardhan Exception - Defined An desirable/ abnormal situation which prevail inside the program is called as an Exception. In general when ever exception occurs the program suddenly stops. This leads to a major problem when working with files, databases, network connections…. Exception handling is a technique or mechanism of handling seriousness of the exception. Traditional programming languages lack of exception handling mechanism. But all modern programming languages are capable of handling the exception Robust programming language
  • 6.
    SSBN Degree College,ATP M Vishnuvardhan Exceptions in java The undesirable condition in java are categorized in to two types 1.Error – Hardware related can’t be handled from the program 2.Exception – Software related can be handled from the program Object Throwable Error Exception StackOver FlowError Virtual MachineError Checked Exception Unchecked Exception UserDefined Exception
  • 7.
    SSBN Degree College,ATP M Vishnuvardhan Categories of Exceptions Exception is the base class of all types of the Exceptions Checked Exception:- Must be handled by the programmer other wise compile time error is generated Unchecked Exception:- It may or may not be handled by the programmer no compile time error is generated. RunTimeException is the base class of all unchecked Exceptions User Defined Exceptions:- In general java deals with common types of exception for a specific type of exception. The programmer has to define the exceptions of the specific type those are called as User-defined Exceptions
  • 8.
    SSBN Degree College,ATP M Vishnuvardhan Checked Exceptions Exception FileNotFoundException IllegalThreadStateException InterruptedException IOException SQLException
  • 9.
    SSBN Degree College,ATP M Vishnuvardhan Checked Exceptions FileNotFoundException: Occurs when an attempt is made to open a file which is not actually present. IllegalThreadStateException: Occurs when a thread is moved to an illegal state InterruptedException: Occurs when a Thread is interrupted. IOException: Occurs due to the failure of the h/w or s/w associated with the I/O devices etc., SQLException: Occurs when a database connection is not available or when it returns null.
  • 10.
    SSBN Degree College,ATP M Vishnuvardhan RunTimeException RunTimeException ArithmeticException NumberFormatException NullPointerException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException
  • 11.
    SSBN Degree College,ATP M Vishnuvardhan Runtime Exceptions ArithmeticException: Occurs when a number is divided by zero e.g.: int c=20/0; ---> ArithmeticException NumberFormatException: Occurs an attempt is made to convert String with invalid digits to number e.g.: String s="123abc"; int x= Integer.parseInt(s); -- > NumberFormatException NumberFormatException: Occurs when a reference is used with out instance E.g.: Rectangle r1; //Object is not initialized. r1.display();
  • 12.
    SSBN Degree College,ATP M Vishnuvardhan Runtime Exceptions ArrayIndexOutOfBoundsException: Occurs when an array is referred beyond the boundaries e.g: int a[]={10,20,30,40,50}; System.out.println(a[20]); //referring the array beyond boundaries ArrayStoreException: Occurs when an attempt is made to store wrong type of object is stored in array of objects. Eg: String s[]=new String [5]; s[0]=new Integer(75); // storing integer object in String array StringIndexOutOfBoundsException: Occurs when a String is referred beyond the string boundaries. e.g. String s=“Java Program”; char ch =s.charAt(23); // referring String beyond the boundaries
  • 13.
    SSBN Degree College,ATP M Vishnuvardhan Exception Handling in Java Exception handling in java can be done with the help of keywords like try, catch, finally, throw, throws try { ------- ------- } catch(ExceptionClass 1) { } catch(ExceptionClass 2) { } ---- ----- ----- catch(ExceptionClass n) { } finally { }
  • 14.
    SSBN Degree College,ATP M Vishnuvardhan Exception Class Methods  String getMessage(): returns the message returns associated with the Exception  String toString(): prints the exception name as well as the message associated with the exception  void printStackTrace(): prints the exception name, message associated with it, line number in which the exception is present and the method name where the statement is present and class where the method is located i.e..., full details
  • 15.
    SSBN Degree College,ATP M Vishnuvardhan finally block A try block may contain any number of catch blocks but it contains at most one finally block. The finally block is executed at least once whether the exception occurs or not in the try block. In general the try hold the statements like closing of files, closing of streams, closing of the database connection and network connections.
  • 16.
    SSBN Degree College,ATP M Vishnuvardhan User defined Exceptions Java deals the general type of the exceptions which commonly occur in the program. For an application type or a specific type of exception we need to create our own exceptions. These exception are called as user defined exceptions Steps to create User defined exception Create a class by extending from Exception class If needed override any one of the Exception class methods Check the condition for occurring of the exception Create and object for the Exception and manually throw it using throw keyword
  • 17.
    SSBN Degree College,ATP M Vishnuvardhan throw keyword throw:- It is used to throw and exception from the try block towards the catch blocks manually. Most of the it is used with user defined exceptions where exception must be manually throw from try block. Syntax : throw new ExceptionClassName(<<Params>>); E.g.: throw new ArithmeticException();
  • 18.
    SSBN Degree College,ATP M Vishnuvardhan throws keyword throws:- It is generally used to postpone the exception handling. Generally used at the method declaration to list the exception which occur in the method. Any one who uses the method must and should handle the exception listed E.g.: public void test () throws IOException { ====== } public static void main(String args[]) { try { test() ---- } catch(IOException e) { --- } }
  • 19.
    SSBN Degree College,ATP M Vishnuvardhan Questions