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

Exception Handling

The document provides an overview of exception handling in Java, detailing the types of exceptions, including checked and unchecked exceptions, and the mechanisms for handling them such as try-catch blocks and the throw statement. It explains the importance of managing errors to maintain the normal flow of applications and includes examples of how to implement exception handling in code. Additionally, it covers creating custom exceptions and the use of finally blocks for cleanup operations.

Uploaded by

Deep K
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)
3 views

Exception Handling

The document provides an overview of exception handling in Java, detailing the types of exceptions, including checked and unchecked exceptions, and the mechanisms for handling them such as try-catch blocks and the throw statement. It explains the importance of managing errors to maintain the normal flow of applications and includes examples of how to implement exception handling in code. Additionally, it covers creating custom exceptions and the use of finally blocks for cleanup operations.

Uploaded by

Deep K
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/ 37

Exception Handling

● Errors should be handled by the


programmer, to prevent them from reaching
the user.
● Some typical causes of errors:
Memory errors (i.e. memory incorrectly
allocated, memory leaks, “null pointer”)
File system errors (i.e. disk is full, disk has
been removed)
Network errors (i.e. network is down, URL
does not exist)
Calculation errors (i.e. divide by 0)

An exception is an abnormal condition that arises in a code


sequence at run time. In other words, an exception is a
run-time error.
The exception handling in java is one of the
powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.

● When an exceptional condition arises, an object


representing that exception is created and thrown in the
method that caused the error.
• public class Testtrycatch1{ • ou
• public static void main(String args[]){ tp
• int data=50/0;//may throw exception ut
• System.out.println("rest of the code...");
• }
• }

• Output:
• Exception in thread main
java.lang.ArithmeticException:/ by zero
Hierarchical Structure of
Throwable Class
Definition of Exception
• Error Class
– Critical error which is not acceptable in
normal application program

• Exception Class
– Possible exception in normal application
program execution
– Possible to handle by programmer
Java’s Built-in Exceptions
● Inside the standard package java.lang, Java defines several
exception classes

The most general of these exceptions are subclasses of the standard


type RuntimeException.

● Since java.lang is implicitly imported into all Java programs,


most exceptions derived from RuntimeException are
automatically available. Furthermore, they need not be included
in any method’s throws list In the language of Java, these are
method s list. called unchecked exceptions because the compiler does
not check to see if a method handles or throws these exceptions.

● Checked exceptions defined by java.lang that must be included in


a method’s throws list if that method can generate one of these
exceptions and does not handle it itself.
Unchecked Exceptions
Checked Exceptions
System-Defined Exception
• Raised implicitly by system because of
illegal execution of program
• When cannot continue program
execution any more
• Created by Java System automatically
• Exception extended from Error class and
RuntimeException class

 [DivByZero.java]
System-Defined Exception
• IndexOutOfBoundsException :
– When beyond the bound of index in the object which use index, such as
array, string, and vector
• ArrayStoreException :
– When assign object of incorrect type to element of array
• NegativeArraySizeException :
– When using a negative size of array
• IOException:
– Caused by IO failiures.
• FileNotFoundException:
• IllegalMonitorStateException :
– When the thread which is not owner of monitor involves wait or notify
method
Programmer-Defined Exception
Exceptions raised by programmer
• Check by compiler whether the
exception handler for exception
occurred exists or not
– If there is no handler, it is error

• Sub class of Exception class


class Exc0
{ public static void main(String args[]) {
int d = 0;
int a = 42 / d; }}

● When the Java run-time system detects the attempt to divide by


zero, it constructs a new exception object and then throws this
exception. This causes the execution of Exc0 to stop, because once
an exception has been thrown, it must be caught by an exception
handler and dealt with immediately.

● Any exception that is not caught by your program will ultimately be


processed by the default handler. The default handler displays a
string describing the exception, prints a stack trace from the point at
which the exception occurred, and terminates the program.

● Here is the output generated when this example is executed.


java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Try Catch
Exception handling is accomplished through the “try –
catch” mechanism, or by a “throws” clause in the
method declaration.

Try-Catch Mechanism
● Handling exception by yourself provides 2 benefits.
First, it allows you to fix the error. Second, it prevents
the program from automatically terminating.

● To guard against and handle a run-time error, simply


enclose the code that you want to monitor inside a try
block.
● Immediately following the try block, include a catch
clause that specifies the exception type that you wish
to catch.
● Syntax

try { //… normal program code


}
catch(Exception e) {
… exception handling code
}
class Exc2 {
public static void main(String args[]) {
int d, a;

try { // monitor a block of code.


d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}

catch (ArithmeticException e) {
System.out.println("Division by zero."); }
System.out.println("After catch statement."); } }

/* This program generates the following output:


Division by zero.
After catch statement.*/
Displaying Description of an
Exception
You can display the description of an exception in a println( )
statement by simply passing the exception as an argument.

● For example, the catch block in the preceding program can


be
rewritten like this:

catch (ArithmeticException e) {
System out println("Exception: " + e);
a = 0; // set a to zero and continue }

● When this version is substituted in the program, and the


program is run, each divide-by-zero error displays the
following message:
Exception: java.lang.ArithmeticException: / by zero
Multiple catch clauses
• In some cases, more than one
exception could be raised by a single
piece of code. To handle this situation,
you can specify two or more catch
clauses, each catching a different type
of exception.
• When an exception is thrown, each
catch statement is inspected in order,
and the first one whose type matches
that of the exception is executed.
• After one catch statement executes,
the others are bypassed,and execution
continues after the try/catch block.
Demonstrate multiple catch
statements
class MultiCatch
{public static void main(String args[]) {
try {
int a[]={5,10};

int b = 5;
int x=a[2] /b-a[1];}

catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);

} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e); }

catch(Exception e)
{System.out.println("common task completed");} }
Nested Try
● The try statement can be nested. That is, a try statement can be
• inside the block of another try.
• Sometimes a situation may arise where a part of a block may
cause one error and the entire block itself may cause another
error. In such cases, exception handlers have to be nested.

● Each time a try statement is entered, the context of that


exception is pushed on the stack. If an inner try statement does
not have a catch handler for a particular exception, the stack is
unwound and the next try statement’s catch handlers are
inspected for a match. This continues until one of the catch
statements succeeds, or until all of the nested try statements are
exhausted.
● If no catch statement matches, then the Java run-time system
will handle the exception
• Syntax:
• ....
• try
• {
• statement 1;
• statement 2;
• try
• {
• statement 1;
• statement 2;
• }
• catch(Exception e)
• {
• }
• }
• catch(Exception e)
• {
• }
• ....
Nested try example
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[0]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e
);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Finally
• finally creates a block of code that will be executed after a
try/catch block has completed and before the code following
the try/catch block.

• The finally block will execute whether or not an exception


is thrown.
• If an exception is thrown, the finally block will execute even if
no catch statement matches the exception.

• Finally block in java can be used to put "cleanup" code such as


closing a file, closing connection etc.

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.

• ● The finally clause is optional. However, each try


statement requires at least one catch or a finally clause.
public class TestFinally{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{System.out.println(e);}

finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main
java.lang.ArithmeticException:/ by zero finally block is
always executed rest of the code...
Throw
● Instead of Java Run-Time system, it is also possible for your program to
throw an exception explicitly, using the throw statement. The
general form of throw is shown here:

throw ExceptionObject;

● 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.
// Demonstrate throw.
class ThrowDemo {
int age=8;
void demoproc() {
try {
if (age<10)
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("Caught: Enter a valid age");
}}

Class Test
public static void main(String args[]) {

ThrowDemo ob =new ThrowDemo();


Ob.demoproc();
}
Output:
• "Caught: Enter a valid age;.
Throws
• Its an alternative to try –catch exceptional handling
mechanism.
• We can include a throws clause in a method declaration.
• A throws clause lists the types of exceptions that a
method 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, a compile-time error
will result.
● This is the general form of a method declaration
that includes a throws clause:

type method-name(parameter-list) throws


exception-list
{ // body of method }
● Here, exception-list is a comma-separated list of
the exceptions that a method can throw.

Eg. Void calculate() throws IOException,SQLexception


class ThrowsDemo {
static void throwOne() throws ArithmeticException
{
System.out.println("Inside throwOne.");
int x=22/0;
}
}
class Hello{
public static void main(String args[]) {
throwOne();
}}
Throw v/s Throws
throw keyword throws keyword
1)throw is used to explicitly throw an throws is used to declare an exception.
exception.

Syntax: throw exceptionobject Syntax:type method-throws exception-


list
{ // body of method }

2)throw is followed by an instance. throws is followed by class.


3)throw is used within the method. throws is used with the method signature.

4)You cannot throw multiple exception You can declare multiple exception e.g.
public void method()throws
IOException,SQLException.
Exceptions fall into two categories:
Checked Exceptions
Unchecked Exceptions
1) Unchecked Exception
The exceptions that are not checked at compile time are called unchecked
exceptions, classes that extends RuntimeException comes under unchecked
exceptions.

2) CheckedExceptions
Exceptions that are checked at compile-time are called checked exceptions, in
Exception hierarchy all classes that extends Exception class except
UncheckedException comes under checked exception category.

try {
String input = reader.readLine();
System.out.println("You typed : "+input); // Exception prone area
}
catch (IOException e) {}

While writing a code to read or write something from files or even from or to
console, an checked Exception i.e. IOException is thrown, these exceptions are
checked at compile time and we are forced to write a handler at compile time.
That’s why we called these exceptions Checked Exceptions.
class FinallyDemo {// 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");}} // 1st finally (after exception thrown)

static void procB() {


try
{System.out.println("inside procB");
return; }
finally { //2nd finally after no exception
System out println("procB's finally");}}

static void procC() {


try {
System.out.println("inside procC");}
finally {
System.out.println("procC's finally");}} // 3rd finally

public static void main(String args[]) {


try {
procA();}

catch (Exception e) {
System.out.println("Exception caught");}
procB();
procC();}}
Creating your own Exception
subclasses
● We can create our own exception
types to handle situations specific to your applications.

● Just define a subclass of Exception (which is, of course, a subclass


of Throwable). Your subclasses don’t need to actually
implement anrhing.
● The Exception class does not define any methods of its own.
It does, of course, inherit those methods provided by
Throwable. Thus, all exceptions, including those that you create,
have defined by Throwable available to them.
Methods defined by Throwable
class MyException extends Exception {

public String toString() // provide a desc. Of your exception


{return "MyException: Invalid age";
}}

class ExceptionDemo{
public static void main(String args[]) {

try{

Scanner sc=new Scanner(System.in);


int age=sc.nextInt();
if(age < 1)
throw new MyException();

System.out.println("No Exception");}
catch (MyException e) {
System.out.println("Caught " + e);}}}
.Contd

You might also like