CH2 Exception Handling

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Advanced Object Oriented

Programming

Chapter Two

Exception Handling

1
Introduction

• An exception is an event that occurs during the execution of a program


that disrupts the normal flow of instructions.
• an exception is a run-time error.
• Java facilitates the management of such errors by diverting control to
special program blocks that are called exception handlers.
• In many cases, handling an exception allows a program to continue
executing as if no problem had been encountered.
• Exceptions can be generated by the Java run-time system, or they
can be manually generated by your code.

2
The Causes of exception
• An exception is thrown for one of the three reasons:

(a) An abnormal execution condition was detected by the JVM. Such


conditions arise because:
Evaluation of an expression violates the normal semantics of the
Java language, such as an integer divided by zero.
An error occurs in loading or linking part of the Java program
Some limitation at recourse is executed, such as using too much
memory

(b) A throw statement was executed in Java code

(c) An asynchronous exception occurred either because


The method stop of class Thread was invoked
An internal error has occurred in the virtual machine.
3
The Throwable Class Hierarchy
• A Java exception is an instance of the Throwable class or one of its
extensions. Such an object can be instantiated by running program in
two ways.

 When an exception is thrown, it can be caught by a catch clause


of a try statement. Using a try statement to catch an exception is
called exception handling.

The figure in the next slide depicts the inheritance hierarchy of


the Throwable class.

4
Contd. Throwable

Error Exception

ClassNot Runtime CloneNotSupported


IOExceotion found Exception Exception
Exception
Arithmetic
Exception
ClassCast
EOFException Exception IllegalArgument
Exception
IllegalState
FileNot found Exception NumberFormat
Exception Exception
IndexOutOf arrayIndexOutOf
Malformed URL Bouds Exception Bounds Exception
Exception
NoSuchElement inputMisMatch
UnknowHost Exceotion Exception
Exception NullPointer
Exception 5
Checked Vs Unchecked Exceptions

• There are two kinds of exceptions.

• The first kind is called unchecked exceptions. They are instances of


the Error class, the run-time Exception class, and their extensions. For
example, if the division of an integer by zero is attempted, the system
will generate an ArithmeticException.

• Exceptions of the second kind are called checked exceptions


because they are “checked” by the compiler before the program is
run. Statements that throw them either must be placed within a try
statement, or they must be declared in their method’s header. Checked
exceptions are the kind that should be expected and therefore
managed by an exception handler. 6
Contd.

7
Contd.

• When you call a method that throws a checked exception, the compiler
checks that you don't ignore it. You must tell the compiler what you are
going to do about the exception if it is ever thrown.

• Checked exceptions are due to external circumstances that the programmer


cannot prevent. The compiler checks that your program handles these
exceptions.

• On the other hand, the compiler does not require you to keep track of
unchecked exceptions.

• All exceptions that belong to subclasses of RuntimeException are


unchecked, and all other subclasses of the class Exception are checked.
8
Contd.
• For example, an unexpected end of file can be caused by forces beyond
your control, such as a disk error or a broken network connection. But
you are to blame for a NullPointerException, because your code was
wrong when it tried to use a null reference.

• Checked exceptions are due to external circumstances that the


programmer cannot prevent. The compiler checks that your program
handles these exceptions.

• The compiler doesn't check whether you handle a NullPointer-


Exception, because you should test your references for null before using
them rather than install a handler for that exception.

9
Handling of an Exception.

• Java exception handling is managed via five keywords: try, catch,


throw, throws, and finally.
• the general try statement in Java has this syntax:

try{
statements;
}catch(exception-type1 idetifier1){
statements;
}catch(exception-type2 identifier2){
statements; }

finally { // block of code to be executed before try block ends
}
10
Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is useful
to see what happens when you don’t handle them. This small program
includes an expression that intentionally causes a divide-by-zero error.
• class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d; }
}
• Here is the output generated when this example is executed.

• What does the above error code refer to?


11
Contd.
• Notice how the class name, Exc0; the method name, main; the
filename, Exc0.java;and the line number, 4, are all included in the
simple stack trace.
• Also, notice that the type of the exception thrown is a subclass of
Exception called ArithmeticException, which more specifically
describes what type of error happened.
• The stack trace will always show the sequence of method
invocations that led up to the error. For example, here is another
version of the preceding program that introduces the same error but in
a method separate from main( ):
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d; }
public static void main(String args[]) {
Exc1.subroutine(); } }
12
Contd.
• The resulting stack trace from the default exception handler shows how
the entire call stack is displayed:

13
Using try--- catch block

• Handling an exception provides two benefits.


• First, it allows you to fix the error.
• Second, it prevents the program from automatically terminating.

• Most users would be confused (to say the least) if your program stopped
running and printed a stack trace whenever an error occurred! Fortunately,
it is quite easy to prevent this.

14
Contd.
• let us consider how to handle an exception using try-catch
statement: The following code contains an intentional error.
class Exc2 {//… Example1:-handling Exception
public static void main(String args[]) {
int d, a;
Output??
try { d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero."); }
System.out.println("After catch statement."); }
}
This program generates the following output:
• Division by zero.
• After catch statement. 15
Contd.
• What is the possible type of exceptional event that will occur in the
following code fragment ?
try
{
System.out.println("How old are you?");
int age = in.nextInt() ;
System.out.println("Next year, you'll be " + (age + 1));
}
catch (InputMismatchException e)
{
e.printStackTrace();
}

 Ans. Input mismatch. The user may type a non numeric value(such
as a string) for the age value(which needs to be an integer type).
16
Multiple Catch Clauses
// Demonstrate multiple catch statements.
// Run the following program using the command line
class MultiCatch {
public static void main(String args[]) {
try { int a = args.length; //Output??
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.println("Array index oob: " + e); }
System.out.println("After try/catch blocks."); } }

17
Contd.
• Here is the output generated by running it both ways:

C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

C:\>java MultiCatch group1

a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.

18
Contd.
• In a multiple catch clause only one catch block will be executed(if it
matches with the exception in the try block) or JVM generated
exception will be thrown(if none of the catch blocks matches with the
exception in the try block).

• When you use multiple catch statements, it is important to remember


that exception subclasses must come before any of their
superclasses. This is because a catch statement that uses a superclass
will catch exceptions of that type plus any of its subclasses.

• Thus, a subclass would never be reached if it came after its


superclass. Further, in Java, unreachable code is an error.

• The following program contains an error. A subclass must come


before its superclass in a series of catch statements. If not,
unreachable code will be created and a compile-time error will result.
19
Contd.
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached."); }
}
} /* The second catch is never reached because
ArithmeticException is a subclass of Exception. */

20
throws Keyword

• This keyword is used for exception handling along methods.

• If a method is capable of raising an exception that it does not handle,


it must specify that the exception should be handled by the calling
method. This is done by the throws keyword.
- let us see an example here:
private int quotient(int nume, int deno) throws ArithmeticException
{
return nume/deno;
}

• Any method calling the quotient method must throw an


exception(I,e.ArithmeticException)
21
Contd.
public void CallerMethod(){
try{
num1 = Integer.parseInt(firstNumber); /*Number Format
num2 = Integer.parseInt(secondNumber); Exception */

result = quotient(num1,num2);//throws an ArithmeticException


}catch(NumberFormatException nfe){

System.out.println("Divide by 0: " + nfe);

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

}
}//end of method
22
Contd.

• In the above code, the private method called quotient is declared with
the keyword throws in the method header definition.

• This shows that the statement return nume/deno; in the body of the
method is capable of throwing an ArithmeticException. But, there is
no mechanism to handle the exception inside the method body.
Therefore, any method calling this method should have a means to
handle the exception.

• If your method can throw checked exceptions of different types, you


separate the exception class names by commas:

• Example:-public void read (String filename) throws IOException,


23
ClassNotFoundException
throw Keyword

• The “throw” keyword is used to throw an exception and to terminate


the program.

Syntax
—throw ThrowableInstance;

ThrowableInstance must be an object of type Throwable or a


subclass of Throwable.
Simple types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions.

The flow of execution stops immediately after the throw statement;


any subsequent statements are not executed. 24
Contd.
Example: Use of throw

• suppose someone tries to withdraw too much money from a bank


account.
public class BankAccount
{
public void withdraw(double amount)
{
if (amount > balance)
// Now what???
...
}
...
}

25
Contd.

First look around(in the java library classes) for an appropriate


exception type that might describe your situation.

Which one fits your choice IllegalStateException or


legalArgumentException ?

Is the bank account in an illegal state for the withdraw operation?
Not really—some withdraw operations could succeed. Is the
parameter value illegal? Indeed it is. It is just too large. Therefore,
let's throw an legalArgumentException.

26
Contd.
public class BankAccount
{
public void withdraw(double amount)
{
if (amount > balance)
{
IllegalArgumentException exception
= new IllegalArgumentException("Amount exceeds balance");
throw exception;
}
balance = balance - amount;
}
...
}
27
Contd.
• Actually, you don't have to store the exception object in a variable.
You can just throw the object that the new operator returns:

throw new IllegalArgumentException("Amount exceeds balance");

• When you throw an exception, execution does not continue with the
next statement but with an exception handler .

• When you throw an exception, the current method terminates


immediately.

28
Contd.

29
The finally Clause
• The finally clause is used when you need to take some action whether
or not an exception is thrown in a program.

• Programs that obtain certain types of resources must return those


resources to the system explicitly to avoid so-called resource leaks.

• Java performs automatic garbage collection to remove objects no


longer used by programs, thus avoiding most memory leaks.

• However, other types of resource leaks can occur in Java. For


example, files, database connections and network connections that are
not closed properly might not be available for use in other programs, or
even later in the same program’s execution.
30
Contd.
In the following code segment, we open a writer, call one or more
methods, and then close the writer:

PrintWriter out = new PrintWriter(filename);


writeData(out);
out.close(); // May never get here

Now suppose that one of the methods before the last line throws an
exception. Then the call to close is never executed! Solve this
problem by placing the call to close inside a finally clause
PrintWriter out = new PrintWriter(filename);
try
{ writeData(out); }
finally
{
out.close(); }
31
Contd.
• Once a try block is entered, the statements in a finally clause are
guaranteed to be executed, whether or not an exception is thrown.

• Use the finally clause whenever you need to do some clean up, such
as closing a file, to ensure that the clean up happens no matter how
the method exits.
• When a finally clause comes after one or more catch clause(s),the
code in the finally clause is executed whenever the try block is exited
in any of three ways:

 After completing the last statement of the try block


 After completing the last statement of a catch clause, if this try
block caught an exception
When an exception was thrown in the try block and not caught

32
Contd.
• However, it is recommend that you don't mix catch and finally
clauses in the same try block . Instead, you should use a try/finally
statement to close resources and a separate try/catch statement as
shown in the next code.
try
{ PrintWriter out = new PrintWriter(filename);
try
{
// Write output
}
finally {
out.close(); }
}
catch (IOException exception)
{ // Handle exception }
33
User Defined Exception

• Sometimes none of the standard exception types describe your


particular error condition well enough. In that case, you can design
your own exception class.
• Suppose you accept a user name and a password from a user. While
verifying this information, if the login credentials do not match, you
may need to generate an exception. For this purpose, you can use a
user defined exception.
• A new exception class must extend an existing exception class to
ensure that the class can be used with exception handling mechanism.
Like any other class, an exception class can contain fields and
methods. The subclass of the exception class inherits the methods
provided by the Throwable class because Throwable is the superclass
for the Exception class.
• let us consider an example here:

34
package javaexception;

public class UserDefinedException extends Exception{


public UserDefinedException() {
System.out.println("Wrong data has been entered");
}
public UserDefinedException(String msg){
System.out.println(msg);
}
}

35
package javaexception;
public class UserTrial {
private int num1,num2;
public UserTrial(int a,int b)
{ num1=a;
num2=b;
}
public void show() throws UserDefinedException
{ if(num1<0 || num2>0)
throw new UserDefinedException("Wrong data has been entered");
else
System.out.println("You entered : "+num1+" and "+num2);
}
}
36
package javaexception;
public class Main {
public Main() {
}
public static void main(String[] args) {
UserTrial trial = new UserTrial(-1, 1);
try{
trial.show();
}catch(UserDefinedException ude){
System.err.println("Illegal values entered");}
}
}

37

You might also like