Exception Handling in Java
Exception Handling in Java
1 2
3 4
5 6
1
8/30/2017
7 8
9 10
11 12
2
8/30/2017
Position of error: class name and method name (Filename: Line Number)
13 14
15 16
17 18
3
8/30/2017
19 20
Rule for using multiple catch clauses Superclass exception as a first catch
• When we use multiple catch statements, the exception
subclasses must come before any of their super-classes
• A catch statement that uses a superclass will catch
exceptions of that type plus any of its subclasses.
• Thus any subsequent catch clauses are never reached –
called unreachable code.
• In Java, unreachable code is error. Therefore, such
program would not get compiled.
21 22
23 24
4
8/30/2017
}
}
27 28
29 30
5
8/30/2017
31 32
33 34
35 36
6
8/30/2017
37 38
39 40
41 42
7
8/30/2017
43 44
45 46
8
8/30/2017
49 50
9
8/30/2017
55 56
57 58
Account
Account
(cont…)
class Account{ public void withdraw(double amount)throws
private int ID; NegativeAmountException,
private double balance;
Account(int ID,double balance){ InsufficientFundException{
this.ID=ID; if(amount<0)
this.balance=balance; throw new
} NegativeAmountException(this,amount,"withdraw");
public int getID(){
return ID; if(balance<amount)
} throw new InsufficientFundException(this,amount);
public double getBalance(){ balance=balance-amount;
return balance;
} }
59 60
10
8/30/2017
Account
NegativeAmountException
(cont…)
public void deposit(double amount)throws class NegativeAmountException extends Exception{
NegativeAmountException{ private Account account;
if(amount<0) private double amount;
throw new
private String transactionType;
NegativeAmountException(this,amount,"deposit"); public NegativeAmountException(Account account,double
amount,String tt){
balance=balance+amount; super("Negative amount");
} this.account=account;
public String toString(){ this.amount=amount;
return "Account: ID="+ID+";Balance="+balance; this.transactionType=tt;
} }
}
}
61 62
InsufficientFundException TestAccount
class InsufficientFundException extends Exception{ public class TestAccount{
private Account account; public static void main(String[] args){
private double amount; Account ac=new Account(1,1000);
public InsufficientFundException(Account account,double amount){ System.out.println("Deposit -100 in "+ac);
super("Insufficient balance"); try{
this.account=account; ac.deposit(-100);
this.amount=amount; }
} catch(NegativeAmountException e){
public String toString(){ System.out.println(e);
return "InsufficientFundException: Available balance = }
"+account.getBalance()+" requested amount="+amount;
}
63 64
}
TestAccount
Running the TestAccount
(cont…)
System.out.println("Widthdraw 1100 from "+ac);
try{
ac.withdraw(1100);
}
catch(NegativeAmountException e){
System.out.println(e);
}
catch(InsufficientFundException e){
System.out.println(e);
}
}
}
65 66
11