Exceptions: An OO Way For Handling Errors I Ntroduction: Without Error Handling - Example 1
Exceptions: An OO Way For Handling Errors I Ntroduction: Without Error Handling - Example 1
Exceptions:
Rarely does a program runs successfully at its
An OO Way for Handling very first attempt.
Errors It is common to make mistakes while
developing as well as typing a program.
Such mistakes are categorised as:
Rajkumar Buyya
1 2
Trying to store incompatible data elements. public static void main(String[] args){
opening a file in “read mode” that does not exist or no read System.out.println(“Result is “ + a/b);
permission
Any more …. No compilation errors. While running it reports an error and stops without
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
3 4
An exception is a condition that is caused When the JVM encounters an error such as
by a runtime error in the program. divide by zero, it creates an exception object
and throws it – as a notification that an error
has occurred.
Provide a mechanism to signal errors If the exception object is not caught and
handled properly, the interpreter will display an
directly without using flags. error and terminate the program.
If we want the program to continue with
execution of the remaining code, then we
Allow errors to be handled in one central should try to catch the exception object thrown
part of the code without cluttering code. by the error condition and then take
appropriate corrective actions. This task is
known as exception handling.
7 8
ArithmeticException
ArrayIndexOutOfBoundException
ArrayStoreException
throwing an exception – throws
FileNotFoundException
OutOfMemoryException
StackOverflowException
StringIndexOutOfBoundException
9 10
try Block …
…
Statements that causes
an exception try {
// statements
}
Throws catch( Exception-Type e)
exception
Object {
// statements to process exception
catch Block }
..
Statements that
handle the exception
..
11 12
Finding a Sum of Integer Values
With Exception Handling - Example 3
Passed as Command Line Parameters
class WithExceptionHandling{ / / ComLineSum.java: adding command line parameters
class ComLineSum
public static void main(String[] args){ {
public static void main( String args[ ] )
int a,b; float r; {
int I nvalidCount = 0;
a = 7; b = 0; int number, sum = 0;
} 13 14
If a try block is likely to raise more than one type of exceptions, then
multiple catch blocks can be defined as follows:
Number of Invalid Arguments = 0 …
…
Number of Valid Arguments = 2 try {
/ / statements
Sum of Valid Arguments = 3 }
catch( Exception-Type1 e)
{
[ raj@mundroo] java ComLineSum 1 2 abc }
/ / statements to process exception 1
15 16
throw exception-object;
..
finally {
OR
….
}
21 22
23 24
User-Defined Exceptions in standard
Summary
format
class MyException extends Exception
{
}
}
Summary
27