CH2 Exception Handling
CH2 Exception Handling
CH2 Exception Handling
Programming
Chapter Two
Exception Handling
1
Introduction
2
The Causes of exception
• An exception is thrown for one of the three reasons:
4
Contd. Throwable
Error Exception
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.
• On the other hand, the compiler does not require you to keep track of
unchecked exceptions.
9
Handling of an Exception.
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.
13
Using try--- catch block
• 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.
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).
20
throws Keyword
} 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.
Syntax
—throw ThrowableInstance;
25
Contd.
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:
• When you throw an exception, execution does not continue with the
next statement but with an exception handler .
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.
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:
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
34
package javaexception;
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