0% found this document useful (0 votes)
5 views

Exception Handling

The document provides an overview of exception handling in Java, detailing how exceptions are created, caught, and managed using keywords like try, catch, throw, throws, and finally. It explains the syntax for handling exceptions, including multiple catch clauses and custom exceptions, along with sample programs to illustrate these concepts. Additionally, it lists built-in exceptions and their meanings, emphasizing the importance of exception handling in maintaining program stability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Exception Handling

The document provides an overview of exception handling in Java, detailing how exceptions are created, caught, and managed using keywords like try, catch, throw, throws, and finally. It explains the syntax for handling exceptions, including multiple catch clauses and custom exceptions, along with sample programs to illustrate these concepts. Additionally, it lists built-in exceptions and their meanings, emphasizing the importance of exception handling in maintaining program stability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

EXCEPTION:

> 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

Syntax of Exception Handling Code: within the try


try The program statements that are to be monitored for exceptions are contained
block.
manner.
catch: The thrown exception from try block is caught in this block in some rational
throw: It is used to manually throw an exception.
CnrowS: Any exception that is thrown out of a method must be specified as such by a throwS
clause.
TInaiy Any code that absolutely must be executed before a method returns is put in a finally
block.

General Syntax of Exception-Handling block:


try

I/ block of code to monitor for errors

catch (ExceptionTypel exOb)

/ exception handler for ExceptionTypel

catch (Exception Type2 exOb)


{
Ilexception handler for ExceptionType2
}

finally
I/block of code to be executed before try block ends

Here, Exception Type isthe type of exception that has occurred.

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

MULTIPLECATCH CLAUSE: code.


> Insome cases, more than one exception could be raised byasingle piece of
> To handle this type of situation, you can specity two or more catch clauses, each catching a
different type of exception. one
PWhen an exception is thrown, each catch statement is inspected in order, and the Tirst
whose type matches that of the exception is executed.
execution continues arter
ATter one catch statement executes, the others are bvpassed, and
the try/catch block.

Sample Program:
class MultiCatch

public static void 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("Divide by 0: " +e);


catch(ArrayindexOutOfBoundsException e)
System.out,printn("Array index oob: " + e);

System.outprintln("After try/catch blocks.");

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

Java run time environment. thrown automatically


by
Uowever, possible for your program to thnrow an exception explicitly, usingthe throw
it is
statement.
"> The general form of throw is as shown below:

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.

Working of throw clause:


The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.
> The nearest enclosing try block is inspected to see if it has a catch statement that matches
the type of the exception. If it does find a match, control is transferred to that statement.
> If not, then the next enclosing try statement is inspected, and so on.
> If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.

Sample Program:
class ThrowDemo

static void demoproc)


{
try
{
throw new NullPointerException("demo");

catch(NullPointerException e)
System.out.println("Caught inside demoproc.");
throw e; I/rethrow the exception

public staticvoid main(String args)


try
demoproc(0:

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

such as String and


Simple types, such as int or char, as well as non-Throwable classes,
Object, cannot be used as exceptions.

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:

Return-type method-name(parameter-Iist) throws exception-lIst


{
1/body of method

> Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Sample Program:
class ThrowsDemo

static void throwOne() throws IlegalAccessException

System.out,println("Inside throwOne.");
throw new IlegalAccessException('demo");

public static void main(String argsl)

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");

I/ Return from within a try block.

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'");

I/Execute a try block normally.


static void procc)

try

System.out.println("inside procC");

finaly
System.out.println("procC's finaly");

public static void main(String args[I)

try
{
procA0;

catch (Exception e)
{
System.out.println("Exception caught");

procB);
procc);
}

www.studylinkclasses.com enquiry@studylin kclasses.com 72


Output:
Study LinkThe Best... Is
Next

inside proCA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally

Each try statement requires at least one catch or a finally clause.

Java's Built in Exception:


Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayindexOutOfBoundsException Array index is out-of-bounds.
Assignment to an array element of an
ArrayStoreException
incompatible type.
ClassCastException Invalid cast.

IlegalArgumentException Ilegalargument used to invoke a


method.

IlegalMonitorStateException Illegal monitor operation, such as


waiting on an unlocked thread.
IllegalThreadStateException Requested operation not compatible
with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
Invalid conversion of a string to a
NumberFormatException numeric format.

73
O www.studylinkclasses.com | [email protected]
Study Link The Best... Is Next

CREATING OUR OWN EXCEPTION:


extends Exception class.
Plo create our own exception we declare a class thattime
java's run environment, hence we need to
Our own exception cannot be thrown by
use throw keyword.

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)

throw new MyException("Number is too small");

catch (MyException ob)


{
System.out,println("Caught My Exception");
System.out.println(o b);
}
finally
{
System.out.printIn ("I am always here");

Output:
Caught My Exception
MyException: Number is too smal
Iam always here

You might also like