Some of the common exceptions are:
•Dividinganintegerbyzero.
•Accessinganelementthatisoutoftheboundsofanarray.
•Tryingtostoreavalueintoanarrayofanincompatibleclassortype
•Tryingtocastaninstanceofaclasstooneofitssubclasses.
•Passingaparameterthatisnotinavalidrangeorvaluefora
method.
•Attemptingtouseanegativesizeforanarray.
•Accessingacharacterthatisoutofboundsofastring.
•Convertinginvalidstringtoanumber.
Example:
// This program illustrates the run-time errors
classError_Runtime
{
publicstatic voidmain(String args[ ])
{
inti = 10 ;
intj = 2 ;
int k = i/(j-j); // Division by zero
System.out.println("\n k = " + k);
intl = i/(j+j);
System.out.println("\n l = " + l);
}
}
Theaboveprogramissyntacticallycorrectandthereforedoesnot
produceanyerrorduringcompilation.
However,whentheprogramisrun,itdisplaysthefollowingmessage
andstopswithoutexecutingfurtherstatements.
Division by zero
JavaExceptions:Someofthecommonexceptionsarelisted
inthefollowingtable:
Exception Meaning
ArithmeticException Arithmetic error, such as divide by zero.
ArrayIndexOutOfBoundsException Array index is out of bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
FileNotFoundException Attempt to access a nonexistent file.
IOException Caused by general I/O failures, such as
inability to read from a file.
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings
and number fails.
OutOfMemoryException Caused when there is not enough memory
to allocate a new object
StringIndexOutOfBoundsException Caused when a program attempts to
access a nonexistent character position in a
string.
SerurityException Caused when an applet tries to perform an
action not allowed by the browser’s security
setting.
StackOverflowException Caused when the system runs out of the
stack space.
SyntaxofExceptionHandlingCode:Thebasicconceptof
exceptionhandlingisthrowinganexceptionandcatchingit.
tryblock
Statement that causes an
exception
catchblock
Statement that handles the
exception
Throws exception
object Exception object creator
Exception handling mechanism
Cont.
•Java uses a keyword try to preface a block of code that is likely to cause an
error condition and throw an exception.
•A catch block defined by the keyword catchcatches the exception thrown by the
tryblock and handles it appropriately.
•The catch block is added immediately after the tryblock.
•The general form of exception handling block is:
try
{
// Block of code to monitor for errors
}
catch(Exception-type1 exOb)
{ // Exception handler for Exception Type1 }
catch(Exception-type2 exOb)
{ // Exception handler for Exception Type2 }
…………….
…………….
finally
{ // Block of code to be executed before try block ends}
•Here, Exception-typeis the type of exception that has occurred.
Nowconsiderthefollowingprogram,thatillustratestheuse
ofthetryandcatchtohandleexception.
// This program illustrates the use of the try and catch for exception handling
class TryCatch
{
public staticvoid main(String args[ ])
{
int i = 10 ;
intj = 2 ;
int k, l ;
try
{
k = i / ( j –j ); // Exception
}
catch(ArithmeticException e) // Exception will be caught here
{
System.out.println("\n Division by zero");
}
l = i/(j+j);
System.out.println (" l = " + l);
}
}
Example:
// This program illustrates the use of the multiple catch statements
class Multiple_Catch
{
public staticvoid main(String args[])
{
try
{
int a = args.length ;
System.out.println(" a = " + a);
int b = 42 / a ;
int c[ ] = {1};
c[42] = 99 ;
}
catch(ArithmeticException e)
{ System.out.println("\n Divide by zero " + e); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(" Array index out of bounds " + e); }
System.out.println(" After the try/catch blocks");
}
}
Use of the finally statement:
•finallystatementisusedtohandleanexception
thatisnotcaughtbyanyofthepreviouscatch
statements.
•finallyblockcanbeusedtohandleanyexception
generatedwithinatryblock.
•Itmaybeaddedimmediatelyafterthetryblockor
afterthelastcatchblock.
•Whenafinallyblockisdefined,thisisguaranteed
toexecute,regardlessofwhetherornotan
exceptionisthrown.
•Thefollowingprogramillustratestheuseofthe
finallystatement.
Example:
// This program illustrates the use of the multiple catch statements
classFinally_Class
{ // Throwing an exception out of the method
static void method1( )
{
try
{
System.out.println("\n Inside method1");
throw new RuntimeException("Example");
}
finally
{ System.out.println("\tfinally block of method1"); }
}
// Return from within a try block
static void method2( )
{
try
{
System.out.println("\n Inside method2");
return ;
}
finally
{ System.out.println("\tfinally block of method2"); }
}
Cont.
// Execute the try block normally
staticvoid method3( )
{
try
{
System.out.println("\n Inside method3");
}
finally
{
System.out.println("\tfinally block of method3");
}
}
public staticvoid main(String args[])
{
try
{
method1( );
}
catch(Exception e)
{
System.out.println("\tException caught");
}
method2( );
method3( );
}
} // End of the class definition
Output:
Inside method1
finally block of method1
Exception caught
Inside method2
finally block of method2
Inside method3
finally block of method3
Throwing own exception:
•Itisalsopossibletothrowourownexceptions.
Thiscanbedonebyusingthekeywordthrowas
follows:
thrownewThrowable_subclass;
•Forexample:
thrownewArithmeticException();
thrownewNumberFormatException();
Example: Program to illustrate the use of throwing an exception
import java.lang.Exception ;
class MyException extendsException
{
MyException(String message)
{ super(message) ; }
}
class User_Exception
{
public staticvoid main(String args[])
{
int x = 5, y= 1000 ;
try
{
floatz = (float)x / (float)y ;
if(z < 0.01)
{
throw newMyException(" Number is too small");
}
}
catch(MyException e)
{
System.out.println("\n Caught my exception");
System.out.println( e.getMessage( ) );
}
finally
{ System.out.println(" I am always here"); }
}
}