Exceptions Handling : Exception , Handling of Exception, Using try-catch ,
Catching Multiple Exceptions , Using finally clause , Types of Exceptions, Throwing Exceptions,
Exception
Exceptions are a mechanism used by many
programming languages to describe what to do when something unreported happens.
Something unreported is an error of some type. Like:
– When a method is invoked with unacceptable arguments – When a network connection fails
Exception
Exceptions handle unexpected situations –
Illegal argument, network failure, or file not found
Conditions that can readily occur in a correct program
are checked exceptions.
These are represented by the Exception class.
Severe problems that normally are treated as fatal or
situations that probably reflect program bugs are unchecked exceptions.
Fatal situations are represented by the Error class. Probable bugs are represented by the
RuntimeException class.
The API documentation shows checked exceptions
Exception Example
1 public class AddArguments {
2 public static void main(String args[]) { 3 int sum = 0;
4 for ( String arg : args ) {
5 sum += Integer.parseInt(arg); 6 }
7 System.out.println("Sum = " + sum); 8 }
Exception Example
java AddArguments 1 2 3 4 Sum = 10
java AddArguments 1 two 3.0 4
Exception in thread "main" java.lang.NumberFormatException:
For input string: "two"
at
java.lang.NumberFormatException.forInputString(NumberForm atException.java:48)
at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at AddArguments.main(AddArguments.java:5)
The try-catch Statement
1 public class AddArguments2 {
2 public static void main(String args[]) { 3 try {
4 int sum = 0;
5 for ( String arg : args ) {
6 sum += Integer.parseInt(arg); 7 }
8 System.out.println("Sum = " + sum);
9 } catch (NumberFormatException nfe) {
10 System.err.println("One of the command-line " 11 + "arguments is not an integer.");
12 }
The try-catch Statement
java AddArguments2 1 two 3.0 4
One of the command-line arguments is not
The try-catch Statement
1 public class AddArguments3 {
2 public static void main(String args[]) { 3 int sum = 0;
4 for ( String arg : args ) {
5 try {
6 sum += Integer.parseInt(arg);
7 } catch (NumberFormatException nfe) {
8 System.err.println("[" + arg + "] is not an integer" 9 + " and will not be included in the sum.");
10 }
11 }
12 System.out.println("Sum = " + sum); 13 }
java AddArguments3 1 two 3.0 4 [two] is not an integer and will not be
included in the sum.
[3.0] is not an integer and will not be included
in the sum.
The try-catch Statement
A try-catch statement can use multiple catch clauses: try {
// code that might throw one or more exceptions Try{}
Catch(){}
} catch (MyException e1) {
// code to execute if a MyException exception is thrown } catch (MyOtherException e2) {
// code to execute if a MyOtherException exception is thrown } catch (Exception e3) {
// code to execute if any other exception is thrown }
The finally Clause
The finally clause defines a block of code that always
executes. try {
startFaucet(); waterLawn(); }
catch (BrokenPipeException e) { logProblem(e);
}
finally {
stopFaucet(); }
Common Exceptions
FileNotFoundException NumberFormatException ArithmeticException
The Handle or Declare Rule
Use the handle or declare rule as follows:
• Handle the exception by using the try-catch-finally block. • Declare that the code causes an exception by using the throws clause.
void trouble() throws IOException { ... }
void trouble() throws IOException, MyException { ... } Other Principles
• You do not need to declare runtime exceptions or errors. • You can choose to handle runtime exceptions.
Writing Exception Subclasses
class OwnCreated extends Exception {
public OwnCreated(String message) {
super(message); }
class Bank {
int balance;
void SetBalance(int bal) {
balance=bal; }
void withdraw(int bal) throws OwnCreated { boolean check=true; if((balance-bal)>0) { check=true; } else
{ check=false; } if(!check) {
Creating Your Own Exceptions
public class OwnException {
public static void main(String[] args) throws OwnCreated, IOException{
Bank b1=new Bank(); b1.SetBalance(5000);
b1.withdraw(6000); }
run:
Exception in thread "main" OwnCreated: Please try again Available balance is low: 5000
at Bank.withdraw(OwnException.java:37)
at OwnException.main(OwnException.java:51) Java Result: 1
throw
It is possible for your program to throw an
exception explicitly, using the throw statement.
The general form of throw is shown here:
Here, 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.
There are two ways you can obtain a
Throwable object:
– using a parameter into a catch clause, – creating one with the new operator.
throw
The flow of execution stops immediately after
the throw statement; any subsequent statements are not executed.
throw
The nearest enclosing try block is inspected
to see if it has a catch statement that matches the type of the exception.
throw
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.
throws
If a method is capable of causing an
exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.
throws
You do this by including a throws clause in the method's
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.
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.
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
This can be useful for closing file handles
and freeing up any other resources that
might have been allocated at the beginning of a method with the intent of disposing of them before returning.
The finally clause is optional. However, each
try statement requires at least one catch or a finally clause.