E xcEption H andling
2.7 CUSTOM EXCEPTION CLASSES
Sometimes it is required to develop meaningful exceptions based on application requirements. Fortunately, Java also allows us to create new exception classes.
Since, only instances of Throwable class (or one of its subclasses) may be thrown, user-defined exception classes must inherit (directly or indirectly) this class. The following is a user-defined exception class that extends Exception class:
class InsufficientAmountException extends Exception { long amount;
InsufficientAmountException(long amount) { this.amount = amount;
} }
To increase readability, it is recommended to append the string “Exception” to the names of all classes that inherit (directly or indirectly) from the Exception class. Here is another example:
class ExcessiveAmountException extends Exception { long amount;
ExcessiveAmountException(long amount) { this.amount = amount;
} }
We can then use these two exception classes just like ordinary exception classes as follows: class Bank {
static long MaximumAmount = 15000;
public void withdraw(long accNo, long amount)
throws InsufficientAmountException, ExcessiveAmountException { long balance = getBalance(accNo);
if(balance < amount)
throw new InsufficientAmountException(amount); if(amount > MaximumAmount)
throw new ExcessiveAmountException(amount); //else withdraw...
}
private long getBalance(long accNo) { return 0;
} }
These exceptions classes can also be used in the catch blocks. The following example illustrates this: class UserException {
public static void main(String args[]) { Bank b = new Bank();
try { b.withdraw(0, 20000); } catch(ExcessiveAmountException e) { System.out.println(e); } catch(InsufficientAmountException e) { System.out.println(e); } } }
If executed, it results in the following output: InsufficientAmountException
EXCEPTION HANDLING 41
KEYWORDS
catch block—Contains code to handle exceptions Checked Exception—A set of exceptions that must
be caught or declared to be thrown
Custom Exception classes—User-defined exception
classes that represent meaningful exceptional situations
Error—A subclass of Throwable that represents serious
problematic scenarios (we shall call them errors) that applications can neither anticipate nor recover from
Exception—A subclass of Throwable that represents
exceptional scenarios that applications can catch and handle
Exception hierarchy—A hierarchy of Java
exception classes that represent various exceptional situations
Exceptions—Exceptional or unusual or abnormal
events that occur during the execution of programs
finally block—Contains code that always gets
executed no matter how try block exited
Nested try-catch— A try, catch or a finally block containing another set of try-catch-finally blocks
Runtime exception—A set of exceptions that need not
be caught or declared to be thrown explicitly
throw—A keyword used to throw an exception
explicitly
Throwable—The root class of Java exception class
hierarchy
throws—A keyword used to specify a set of exceptions
a method might throw during its execution
try block—Used to contain a piece of code to be
examined
Try-with-resource statement—A construct that
allows us to use resources that get closed automatically by the Java Runtime Environment
Unchecked Exceptions—A set of exceptions that
need not be caught or declared to be thrown explicitly
SUMMARY
Exceptions are exceptional/unusual/abnormal events that occur during the execution of programs. Five keywords are used for exception handling—try, catch, throw, throws and finally. A try block contains code to be examined. A try block is followed by one or more catch blocks and/or one finally block. Exceptions are thrown and caught by the respective catch block (if any). The finally block, if present, is always executed irrespective of how try block exits.
In Java, exceptional scenarios are represented by various classes which are organized in a hierarchy. The class Throwable is the root of this class hierarchy. The Throwable class has several useful methods to collect detailed information about an exception. Two subclasses of this class are Exception and Error. The class
Error represents serious problematic scenarios that applications can neither anticipate nor recover from them. The class Exception represents rest of the exceptional scenarios that applications can catch and handle.
Usually, exceptions are categorized into two groups: checked exceptions and unchecked exceptions.
Checked exceptions are those that must be caught or declared to be thrown. Java considers Throwable and any of its subclass that is not also a subclass of either
RuntimeException or Error as checked exceptions. Unchecked exceptions (also called runtime exceptions) are those which need not be caught or declared to be thrown explicitly.
It is also possible to explicitly throw an exception using throw keyword. A method must specify the list
of checked exceptions that it might (directly/indirectly) raise but does not handle them using throws clause.
Java 7 and later provides mechanism known as try with resource statement that enables us to create and use resources that get closed automatically by the Java Runtime Environment.
It is possible for exception handlers to be nested within one another. This means a try, catch or a finally block
can in turn contain another set of try-catch-finally blocks. It is also possible to define custom exception classes which must inherit (directly or indirectly) the class Throwable.
WEB RESOURCES
http://docs.oracle.com/javase/tutorial/ essential/exceptions/ Lesson: Exceptions http://www.tutorialspoint.com/java/java_ exceptions.htmhttp://tutorials.jenkov.com/java-exception- handling/index.html
Java Exception Handling
http://howtodoinjava.com/2013/04/04/java- exception-handling-best-practices/
Java exception handling best practices http://www.journaldev.com/1696/java- exception-handling-tutorial-with-examples- and-best-practices
Java Exception Handling Tutorial with Examples and Best Practices http://www.javaworld.com/article/2076700/ core-java/exceptions-in-java.html Exceptions in Java http://www.javatpoint.com/exception- handling-and-checked-and-unchecked- exception
Exception Handling in Java
http://www.urz.uni-heidelberg.de/ Unterstuetzung/Hinweise/Einzel/Java/ EckelJavaTutor/TIJ311.htm
Error Handling with Exceptions
EXERCISES
Objective-type Questions
1. The class at the top of exception class hierarchy
is
(a) ArithmeticException (b) Throwable
(c) Class (d) Exception
2. What will be the output of the program?
public class Test {
public static void main(String[] args) { try { return; } finally { System.out.println( "Finally" ); } } } (a) Finally (b) Compilation error.
(c) The code runs with no output. (d) An exception is thrown at runtime.
3. What will be the output of the program?
public class Test {
public static void main(String[] args) { try {
int x = 0; int y = 5 / x;
System.out.println("finished"); }catch (ArithmeticException ae) {
System.out.println("Exception"); }catch (Exception e) { System.out.println("Arithmetic Exception"); } } }
(a) Compilation error. (b) finished
(c) Exception
(d) Arithmetic Exception
4. An exception thrown from outside try block will
(a) return the program normally (b) be ignored
(c) terminate the program (d) none of the above
5. Which of the following causes an exception
(a) A run-time error (b) A hardware malfunction (c) An operating system problem (d) A syntax error
6. When does exception occur in Java?
(a) At compilation time (b) At run time (c) Any time
(d) None of the mentioned
7. Which of these keywords is not a part of exception
handling?
(a) try (c) finally (b) catch (d) thrown
8. Which of the following keywords is used to
examine exceptions?
(a) try (c) finally (b) catch (d) throw
9. Which of the following keywords is used to handle
exception?
(a) try (c) throw (b) catch (d) throws
EXCEPTION HANDLING 43
10. Which of the following keywords is used to throw
an exception explicitly?
(a) try (c) throw (b) catch (d) throws
11. The key words used with exception handling are:
(a) try, catch, handle (b) try, hold, finally (c) throw, catch, conclude (d) try, catch, finally
12. Arithmetic Exception is
(a) A checked exception (b) An unchecked exception (c) An error
(d) None of the above
13. Which of following exception is thrown by the
int z=2/0;?
(a) ClassNotFoundException (b) NullPointerException (c) ArithmeticException (d) SecurityException
14. Checked exceptions are processed by
(a) Java compiler (b) Java interpreter (c) Both (a) and (b) (d) None of the above
15. Unchecked exceptions are processed by
(a) Java compiler (b) Java interpreter (c) Both (a) and (b) (d) None of the above
16. Which one of the following statements is
correct?
(a) The ‘try’ block must be followed by a ‘catch’ block.
(b) The ‘try’ block must be followed by a ‘finally’ block.
(c) The ‘try’ block must be followed by either a ‘catch’ block or a ‘finally’ block.
(d) The ‘try’ block must be followed by at least one ‘catch’ block and one ‘finally’ block.
17. Creating an exception object and handling it to
the run time system is called (a) exception handling (b) catching exception (c) passing exception (d) throwing exception
18. Which of the following is an example of runtime
exception?
(a) FileNotFoundException (b) IOException
(c) IllegalClassFormatException (d) ClassCastException
19. Which of the following is the super class of all
exception classes?
(a) Exception (c) RuntimeException (b) Throwable (d) IOException
20. Which of the following blocks gets executed
compulsorily whether exception is caught or not? (a) finally (c) throws
(b) throw (d) catch
21. Which of the following is true of the object thrown
by a throw clause?
(a) It must be an Exception type (b) It must be a Throwable type (c) It must be an Error type (d) It must be a String type
22. Which of the following methods is used to print
the description of an exception? (a) traceException()
(b) printStackTrace() (c) printDescription() (d) printStack()
23. Which of the following exceptions is thrown if
an array element is accessed beyond the array size?
(a) ArrayIndexOutOfBounds (b) IndexOutOfBoundsException (c) IndexOutOfBounds
(d) ArrayIndexOutOfBounds Exception
24. Which of the following is true when we write
custom exception classes? (a) Extend the class Exception (b) Create our own try and catch block (c) Use finally block
(d) Use throws keyword
25. Which of the following is true about the Error and
Exception classes?
(a) The Error class is final and the Exception class is not.
(b) The Exception class is final and the Error is not.
(c) Both classes extend Throwable. (d) Both classes implement Throwable.
26. Predict the output of the following Java program.
class Test {
public static void main(String args[]) { try { throw 2; } catch(int e) { System.out.println ("Exception " + e); } } }
(a) Exception 2 (c) Compilation Error (b) Exception 0 (d) None of the above
27. What will be the output of the program?
public class Test {
public static void main(String[] args) { try {
int x = 0; int y = x / 5;
System.out.println("finished"); }catch (ArithmeticException ae) {
System.out.println("Exception"); }catch (Exception e) { System.out.println("Arithmetic Exception"); } } }
(a) Compilation error (c) Exception
(b) finished (d) Arithmetic Exception
28. Which of the following is thrown by the read()
method of InputStream class? (a) Exception
(b) FileNotFoundException (c) ReadException (d) IOException
29. What will be the output of the following program?
public class Test{
public static void main(String args[]){ System.out.print("Before "); try { }catch(Throwable t){ System.out.print("Inside "); } System.out.print("End "); } }
(a) Before End (b) Before Inside (c) Inside End (d) Before Inside End
30. What causes an IllegalMonitorStateException?
(a) Two threads call a static synchronized method at the same time.
(b) A thread invokes wait() on an object that is already waiting.
(c) A thread invokes notify() on an object that is not waiting.
(d) A thread calls wait() or notify() before acquiring an object’s monitor.
Subjective-type Questions
1. What is the difference between checked and
unchecked exceptions?
2. What is the difference between throw and throws
keyword?
3. What do you mean by exception propagation? 4. What are the two types of exceptions in
Java? What are the differences between them?
5. Why do you use multiple catch blocks? 6. How will you write new exception classes? 7. What is the difference between ‘Exception’ and
‘error’ in Java?
8. Describe the principle of ‘finally’ block. 9. What happens if an exception is not caught? 10. Describe the exception hierarchy in Java
11. What is the difference between
ClassNotFoundException and NoClassDefFoundError?
12. What are the advantages of using exception handling? 13. Why are Errors not checked?
14. Why are Runtime Exceptions not checked? 15. What is meant by ‘re-throwing’ an exception? How
do you re-throw an exception?
16. Write some important methods of Exception Class? 17. What is the usefulness of multiple catch blocks? 18. What is the use of throws keyword?
19. When do you use a catch block and when do you
use a finally block?
20. Write some example scenarios when finally block