Exception Handling
Exception Handling
> An
exception is an event that occurs during the
normal flowof instructions. execution of a program that disrupts the
EXCEPTION
AJava exceptionHANDLING:
is an object that
occurred in a piece of code. describes an exceptional (that is, error)
> When an exceptional condition
condition that has
thrown in the method that causedarises, an object representing that
the error. exception is created and
> That method may
choose to handle the exception itself, or pass it on.
>Either way, at some point, the exception is caught and
> Exceptions can be
generated by the Java run-time system,processed.
generated by your code. or they can be mariually
>Exceptions thrown by Java relate to fundamental errors that
violate the rules of the Java
language or the constraints of the Java execution environment.
> Manually generated exceptions are typically used to
caller of a method.
report some error condition to the
º Java exception handling is managed via five keywords: try, catch,
finally. throw, throws, and
Siudy Link The Best... Is Next
finally
I/block of code to be executed before try block ends
O www.studylinkclasses.com
Menquiry @studylinkclasses.com 66
TRY AND CATCH BLOCK:
Study The Best... 1s
Next
UsING
Althoughthe default exception handler provided by theJava run-time system is useful for
debugging, you will usually want to handle an exception yourself.
two benefits.
> Doing so provides
fix the error.
First, it allows youto
Second, it prevents the program from automatically terminating.
> To guard against and handle arun-time error, simply enclose the code that you want to
monitor inside atry block.
Immediately following the try block, includes a catch clause that specifies the exception
type that you wish to catch,
Sample Program:
class TryCatch
public static void main(String args[)
int d, a;
try
I/monitor a block of code.
d = 0;
a= 42/ d;
System.out.printin("This will not be printed.");
catch (ArithmeticException e)
I/ catch divide-by-zero error
System.out.println("Division by zero.");
System.out. printin ("After catch statement.");
}
Output:
DIVISIon by zero.
After catch statement.
If no catch block would have been found having parameters matching to that of the
thrown exception,then java's built in exception handler would process the thrown
exception.
Uwww.studylinkclasses.com [email protected]
Study Link The Best.. Is Next
Sample Program:
class MultiCatch
try
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a,
int c] = {1 );
c[42] = 99;
catch(ArithmeticException e)
Output:
CA>java MutCatch
a=0
Divide by 0: java.lang.ArithmeticException: /by zero
After try/catch blocks.
C\>java MultiCatch TestArg
a =1
Array index oob:
java.lang.ArraylndexOutOfBoundsException
After try/catch blocks.
Owww.studylinkclasses.com |[email protected]
68
Throw:
Whenever an exception was generated within the try block it was
Sudy Link The Best... Is Next
throw Throwablelnstance,
Here Throwablelnstance must be an object of type Throwable or a subclass of Throwable
There are two ways youcan obtain aThrowable object: using a parameter into a catch
clause, or creating one with the new operator.
Sample Program:
class ThrowDemo
catch(NullPointerException e)
System.out.println("Caught inside demoproc.");
throw e; I/rethrow the exception
69
www.studylinkclasses.com
enquiry @studylinkclasses. com
Suty Link
The Best... Is Next
catch(NullPointerException e)
System.out.println("Recaught:" + e);
Output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
THROWs:
Ifamethod is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can quard themselves against that exception.
This is done by including a throws clause in the method's declaration.
Athrows clause lists the types ofexceptions that amethod might throw.
This is necessary for all exceptions, except those of type Error or RuntimeException, or
any of their subclasses.
"> All other exceptions that a method can throw must be declared in the throws clause.
> If they are not declared, a compile-time error will result.
> Syntax:
> Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Sample Program:
class ThrowsDemo
System.out,println("Inside throwOne.");
throw new IlegalAccessException('demo");
try
V www.studylinkclasses.com [email protected] 70
throwOne);
catch (llegalAccessException e)
WStudy Link
System.out.printin("Caught "+e);
Output:
Lnside throwOne
|Caught java.lang.IlegalAccessException: demo
FINALLY:
finally creates a block of code that will be
and before the code following the try/catchexecuted
block.
after a try/catch block has completed
> The finally block willexecute
> Ifan exception is thrown, the
whether or not an exception is thrown.
finally block wll execute even if no catch statement
the exception. matches
> Any time a method is about to return to
the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just
before the method returns.
> This can be useful for closing file handles and
freeing up
have been allocated at the beginning of amethod with theany other resources that might
intent of disposing of them
before returning.
> The finally clause isoptional.
Sample Program:
class Finally Demo
{
I/ Through an exception out of the method.
static void procA)
try
{
System.out. println("inside procA");
throw new RuntimeException("demo"):
finally
System.out,println('procA's finally");
71
www.studylinkclasses.com |[email protected]
NStudy
static void procB)
try
Link
The Best... Is Next
System.out,println("inside procB");
return;
finally
{
System.out,printIn("procB's finally'");
try
System.out.println("inside procC");
finaly
System.out.println("procC's finaly");
try
{
procA0;
catch (Exception e)
{
System.out.println("Exception caught");
procB);
procc);
}
inside proCA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
73
O www.studylinkclasses.com | [email protected]
Study Link The Best... Is Next
Sample Program:
class MyException extends Exception
MyException(String msg)
super(msg)
class TestException
public static void main(Stringl args)
int x=5,y=1000;
try
float z= (float)x/(float)y;
if (z<0.01)
Output:
Caught My Exception
MyException: Number is too smal
Iam always here