Exception Handling
As human beings, we commit many errors. A software engineer may also commit several errors while designing the project or developing the code. These errors are also called ‘bugs’ and the process of removing them is called ‘debugging’.
Errors in a Java program:
ü There are basically three types of errors in the Java program:
· Compile-time errors
· Run-time errors
· Logical errors
Compile-time errors:
ü There are syntactical errors found in the code, due to which a program fails to compile. For example, forgetting a semicolon at the end of a Java statement, or writing a statement without proper syntax will result in compile-time error.
Program: To demonstrate compile-time error.
class Err
{
public static void main(String args[])
{
System.out.println(“Hi madhav”)
System.out.println(“Compile-time error”)
}
}
Output: C:\Madhava>javac Err.java
Err.java:5: ';' expected
System.out.println("Hi madhav")
^
Err.java:6: ';' expected
System.out.println("Compile-time error")
^
2 errors
ü Compile-time errors are detected by the Java compiler. Detecting and correcting compile-time errors is an easy way as the Java compiler displays the list of errors with the line numbers along with their description.
ü The programmer can go to the statements, check them word by word and line by line to understand where he has committed the errors.
Run-time errors:
ü These errors represent inefficiency of the computer system to execute a particular statement. For example, insufficient memory to store something or inability of the microprocessor to execute some statement come under run-time errors.
Program: To demonstrate Run-time error.
class Err1
{
public static void main()
{
System.out.println(“Hi madhav”);
System.out.println(“Compile-time error”);
}
}
Output: C:\Madhava>javac Err1.java
C:\Madhava>java Err1
Exception in thread "main" java.lang.NoSuchMethodError: main
ü Run-time errors are not detected by the Java compiler. They are detected by the JVM, only at runtime.
Logical errors:
ü These errors depict flaws (an imperfection in a device) in the logic of the program. The programmer might be using a wrong formula or the design of the program itself is wrong.
ü Logical errors are not detected either by Java compiler or JVM. The programmer is solely (without any others being included or involved) responsible for them.
Program: To demonstrate logical error
class Err2
{
public static void main(String args[])
{
double sal = 5000.00;
sal = sal*15/100; // wrong. use this correct formula: sal += sal*15/100;
System.out.println(“Incremented salary:”+sal);
}
}
Output: C:\Madhava>javac Err2.java
C:\Madhava>java Err2
Incremented salary:750.0 // here the output is wrong
Correct output: C:\Madhava>javac Err2.java
C:\Madhava>java Err2
Incremented salary:5750.0 //if we use sal += sal*15/100; this formula
ü By observing the above two outputs, a programmer can guess the presence of a logical error.
Exceptions:
ü A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.
ü When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself.
ü At some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by our code.
ü Manually generated exceptions are typically used to report some error condition to the caller of a method.
ü Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
try, catch, throw, throws and finally keywords:
ü Program statements that we want to monitor for exceptions are contained within a try block.
ü If an exception occurs within the try block, it is thrown. Our code can catch this exception (using catch) and handle it in some rational manner.
ü System-generated exceptions are automatically thrown by the Java run-time system.
ü To manually throw an exception, use the keyword throw.
ü Any exception that is thrown out of a method must be specified as such by a throws clause.
ü Any code that absolutely must be executed before a method returns is put in a finally block.
ü General form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
---------
---------
finally
{
// block of code to be executed before try block ends
}
Here, ExceptionType is the type of exception that has occurred.
Exception Types:
ü All exception types are subclasses of the built-in class Throwable.
ü Exception class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create our own custom exception types.
ü There is an important subclass of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that we write and include things such as division by zero and invalid array indexing.
ü Error defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.
Note: Unchecked exceptions are automatically thrown by Java Runtime System (JRS).
Checked exceptions are explicitly thrown.
Uncaught Exceptions:
ü Before we learn how to handle exceptions in our program, it is useful to see what happens when we don’t handle them.
Ex: class Exception1
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
Output:java.lang.ArithmeticException: / by zero at Exception1.main(Exception1.java:6)
ü When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exception1 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately.
ü In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by our program will ultimately be processed by the default handler.
ü The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.
ü Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero at Exception1.main(Exception1.java:6)
Using try and catch:
· Although the default exception handler provided by the Java run-time system is useful for debugging, we will usually want to handle an exception ourselves.
· Doing so provides two benefits:
1. It allows us to fix the error.
2. It prevents the program from automatically terminating.
· To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, includes a catch clause that specifies the exception type that you wish to catch.
Program: Demonstrate try and catch keywords
class Exception2
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException ae) // catch divide-by-zero error
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output: Division by zero.
After catch statement.
(Q) Can I write Exception handling code inside any loop statements?
Ans: Yes, you can write exception handling code inside any loop statements.
import java.util.Random; //Random generates the numbers randomly
class HandleError
{
public static void main(String args[])
{
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<10; i++)
{
b = r.nextInt();
c = r.nextInt();
try
{
a = 100 / (b/c);
}
catch (ArithmeticException ae)
{
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Output: C:\Madhava>javac HandleError.java
C:\Madhava>java HandleError
Division by zero.
a: 0
Division by zero.
a: 0
Division by zero.
a: 0
a: -100
a: 25
a: -50
a: 100
Division by zero.
a: 0
a: -100
Division by zero.
a: 0
Displaying a description of an Exception:
· Throwable overrides the toString() method (defined by object).So that, it returns a string containing a description of an exception.
· We can display this description in a println() statement by simply passing the exception as an argument.
catch(ArithmeticException ae)
{
System.out.println(“Exception:”+ae);
}
Another way:
catch(Exception e)
{
e.getMessage();
}
Ex: java.lang.ArithmeticException: / by zero at Exception1.main(Exception1.java:6)
Multiple catch Clauses:
ü In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception.
ü When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
Program: // Demonstrate multiple catch statements.
class MultiCatch
{
public static void main(String args[])
{
int a,b;
a = args.length;
try
{
b=10/a;
System.out.println("B = " + b);
if( a==1)
{
int c[]={1,2};
System.out.println(“C[3]:”+c[3]);
}
else
{
int d[]=new int[-10];
}
}//end of try
catch(ArithmeticException ae)
{
System.out.println("Divide by 0: " + ae);
}
catch(ArrayIndexOutOfBoundsException x)
{
System.out.println("Array index oob: " + x);
}
catch(NegativeArraySizeException y)
{
System.out.println("Negative Size of an array”);
}
}
}
Output:
Nested try Statements:
ü The try statement can be nested. That is, a try statement can be inside the block of another try.
ü Each time a try statement is entered, the context of that exception is pushed on the stack.
ü If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted.
ü If no catch statement matches, then the Java run-time system will handle the exception.
Program: Demonstrate Nested try statements.
class NestTry
{
public static void main(String args[])
{
int a,b,c;
a = args.length;
try
{
b = 10 / a;
System.out.println("B = " + b);
try // nested try block
{
c=10/a-1;
System.out.println(“C:”+c);
int d[]={1,2};
System.out.println(“D[3]”+d[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException ae)
{
System.out.println("Divide by 0: " + ae);
}
}
}
Output:
The keyword throw:
· We have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement.
· The general form of throw is:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
· There are two ways we can obtain a Throwable object:
o using a parameter into a catch clause, or
o creating one with the new operator.
· Program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.
Program: Demonstrate throw keyword. or re-throwing an exception
class ThrowDemo
{
static void callme()
{
try
{
System.out.println(“In callme”);
throw new NullPointerException("demo");
}
catch(NullPointerException ne)
{
System.out.println(ne);
throw ne; // rethrow the exception
}
}
public static void main(String args[])
{
try
{
callme();
}
catch(NullPointerException e)
{
System.out.println("Exception Recaught: " + e);
}
}
}
Output:
ü Examine the statement,
throw new NullPointerException("demo");
Here, new is used to construct an instance of NullPointerException.
ü All of Java’s built-in run-time exceptions have at least two constructors:
· one with no parameter and
· one that takes a string parameter.
ü When the second form is used, the argument specifies a string that describes the exception. This string is displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined by Throwable.
The throws keyword:
ü 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.
ü We can do this by including a throws clause in the method’s declaration.
ü throws clause 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.
ü General syntax of a method declaration that includes a throws clause:
return type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can
throw.
ü Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the program does not specify a throws clause to declare this fact, the program will not compile.
Program:// This program contains an error and will not compile.
class ThrowsDemo
{
static void callme()
{
System.out.println("Inside callme");
throw new NullPointerException("demo");
}
public static void main(String args[])
{
callme();
}
}
Output:
ü The corrected example is:
Program:
class ThrowsDemo
{
static void callme() throws NullPointerException
{
System.out.println("Inside callme");
throw new NullPointerException("demo");
}
public static void main(String args[])
{
try
{
callme();
}
catch (NullPointerException ne)
{
System.out.println(ne);
}
}
}
Output: inside callme
java.lang.NullPointerException: demo
finally keyword:
ü 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.
ü Java guarantees that a finally block will execute whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks.
ü Java also guarantees that a finally block will execute if a try block exits by using a return, break or continue statement.
ü The finally block will not execute if the application exits early from a try block by calling method System.exit.
ü The finally clause is optional. However, each try statement requires at least one catch or a finally clause.
Note: A finally block typically contains code to release resources acquired in its corresponding try block; this is an effective way to eliminate resource leaks. For example, the finally block should close any files opened in the try block.
ü If an exception that occurs in a try block cannot be caught by one of that try block's catch handlers, the program skips the rest of the try block and control proceeds to the finally block. Then the program passes the exception to the next outer try blocks normally in the calling method where an associated catch block might catch it. This process can occur through many levels of try blocks.
ü If a catch block throws an exception, the finally block still executes. Then the exception is passed to the next outer try blockagain, normally in the calling method.
Program: Demonstrate finally keyword
class FinallyDemo
{
public static void main(String args[])
{
int a,b;
a = args.length;
try
{
b=10/a;
System.out.println("B = " + b);
}
catch(Exception e)
{
System.out.println(“In catch block”);
System.out.prntln(e);
}
finally
{
System.out.println(“Finally block”);
}
}
}
Output:
Java’s Built-in Exceptions:
ü Inside the standard package java.lang, Java defines several exception classes.
ü The most general of these exceptions are subclasses of the standard type RuntimeException.
ü Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions.
ü Exceptions defined by java.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions.
ü Unchecked exceptions:
Exception | Meaning |
ArithmeticException | Arithmetic error, such as divide-by-zero. |
ArrayIndexOutOfBoundsException | Array index is out-of-bounds. |
ArrayStoreException | Assignment to an array element of an incompatible type. |
ClassCastException | Invalid cast. |
IllegalArgumentException | Illegal argument used to invoke a method. |
IllegalMonitorStateException | Illegal monitor operation, such as waiting on an unlocked thread. |
IllegalStateException | Environment or application is in incorrect state. |
IllegalThreadStateException | Requested operation not compatible with current thread state. |
IndexOutOfBoundsException | Some type of index is out-of-bounds. |
NegativeArraySizeException | Array created with a negative size. |
NullPointerException | Invalid use of a null reference. |
NumberFormatException | Invalid conversion of a string to a numeric format. |
SecurityException | Attempt to violate security. |
StringIndexOutOfBounds | Attempt to index outside the bounds of a string. |
UnsupportedOperationException | An unsupported operation was encountered. |
ü Checked exceptions defined in java.lang:
Exception | Meaning |
ClassNotFoundException | Class not found. |
CloneNotSupportedException | Attempt to clone an object that does not implement the Cloneable interface. |
IllegalAccessException | Access to a class is denied. |
InstantiationException | Attempt to create an object of an abstract class or interface. |
InterruptedException | One thread has been interrupted by another thread. |
NoSuchFieldException | A requested field does not exist. |
NoSuchMethodException | A requested method does not exist. |
Creating our Own Exception Subclasses:
ü If we want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception.
ü The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable.
ü All exceptions, including those that you create, have the methods defined by Throwable available to them.
Method | Description |
Throwable fillInStackTrace( ) | Returns a Throwable object that contains a completed stack trace. This object can be rethrown. |
Throwable getCause( ) | Returns the exception that underlies the current exception. If there is no underlying exception, null is returned. Added by Java 2, version 1.4. |
String getLocalizedMessage( ) | Returns a localized description of the exception. |
String getMessage( ) | Returns a description of the exception. |
StackTraceElement[ ] getStackTrace( ) | Returns an array that contains the stack trace, one element at a time as an array of StackTraceElement. The method at the top of the stack is the last method called before the exception was thrown. This method is found in the first element of the array. The StackTraceElement class gives your program access to information about each element in the trace, such as its method name. Added by Java 2, version 1.4 |
Throwable initCause(Throwable causeExc) | Associates causeExc with the invoking exception as a cause of the invoking exception.Returns a reference to the exception. Added by Java 2, version 1.4 |
void printStackTrace( ) | Displays the stack trace. |
void printStackTrace(PrintStream stream) | Sends the stack trace to the specified stream. |
void printStackTrace(PrintWriter stream) | Sends the stack trace to the specified stream. |
void setStackTrace(StackTraceElement elements[ ]) String toString( ) | Sets the stack trace to the elements passed in elements. This method is for specialized applications, not normal use. Added by Java 2, version 1.4 Returns a String object containing a description of the exception. This method is called by println( ) when outputting a Throwable object. |
Program:User defined exceptions
class MyException extends Exception
{
MyException(String str)
{
super(str);
}
}
class MyExpDemo
{
public static void main(String args[])
{
try
{
throw new MyException(“demo”);
}
catch(MyException me)
{
System.out.println(“User defined exception:”+me);
}
}
}
Output: User defined exception:MyException: demo
Assertions:
ü The assert statement, introduced in J2SE 1.4, consists of a boolean expression the programmer believes to be true when it is executed. If it is not true, Java will throw an AssertionError exception.
ü Assertions are useful in testing and debugging programs.
ü The syntax for assert is:
assert boolean expression;
ü If boolean expression evaluates to false, an AssertionError exception is thrown with no associated message. Alternatively, we can use the syntax:
assert boolean expression : value expression;
where value expression is an expression that returns a value;
ü Assertions are typically used within a default else clause, within an if/else statement, or within a switch statement with no default case.
Program: To demonstrate assertions.
class TestAssert
{
public static void main(String args[])
{
int x=0;
switch (x)
{
case 1: System.out.println(''case 1");
break;
case 2: System.out.println("case 2");
break;
default: assert false : x;
System.out.println("default");
break;
}
System.out.println("carry on");
}
}
ü At runtime, assertion checking is disabled by default. So if x is equal to 0, say, we will get the following result:
Output: default
carry on
ü To enable runtime assertion checking, use the -ea option, as follows:
C:\Madhava> java -ea TestAssert
Exception in thread "main" java.lang.AssertionError: 0
at TestAssert.main(TestAssert.java.12)
1. What is an exception?
Ans: An exception is a condition (typically an error condition) that transfers program execution from a thrower (at the source of the condition) to a catcher (handler for the condition); information about the condition is passed as an Exception or Error object.
2. Why do methods have to declare the exceptions they can throw?
Ans: The simpler answer is that the Java language requires it; the more meaningful answer is that the language requires exception declarations because they enhance the usability and robustness of code as part of an API.
3. What’s the difference between a runtime exception and a plain exception-Why don’t runtime exceptions have to be declared?
Ans: The Java language specifies that all runtime exceptions are exempted from the standard method declarations and compiler checks; such exceptions belong more to the system as a whole than to the method that happens to be executing when the exception is thrown.
4. Given a method that doesn’t declare any exceptions, can I override that method in a subclass to throw an exception?
Ans: No; subclasses must honor the API contract established by their superclasses, and this includes the types of checked exceptions that a method can throw.
5. What are checked and unchecked exceptions?
Ans: The exceptions that are checked at compile-time by the Java compiler are called checked exceptions. The exceptions that are checked by the JVM are called unchecked exceptions.
6. What is Throwable?
Ans: Throwable is a class that represents all errors and exceptions which may occur in Java.
7. What is the superclass for all exceptions?
Ans: Exception is the superclass of all exceptions in Java.
8. What is the difference between an exception and error?
Ans: An exception is an error which can be handled. It means when an exception happens, the programmer can do something to avoid any harm. But an error is an error which can not be handled.
9. What is the difference between throws and throw?
Ans: throws clause is used when the programmer does not want to handle the exception and throw it out of a method. throw clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence, throws and throw are contradictory.
10. Is it possible to re-throw an exception?
Ans: Yes, we can re-throw an exception from catch block to another class where it can be handled.
11. What is the difference between error and an exception? (Repeated question)
Ans: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and we can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
12. How to create custom exceptions?
Ans: Your class should extend class Exception, or some more specific type thereof.
13. If I want an object of my class to be thrown as an exception object, what should I do?
Ans: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
14. If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
Ans: One can not do anything in this scenario. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
15. What happens to an unhandled exception?
Ans: The exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by our program will ultimately be processed by the default handler.
The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.
Another answer: An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.
16. Is it necessary that each try block must be followed by a catch block?
Ans: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
17. If I write return statement at the end of the try block, will the finally block still execute?
Ans: Yes, Even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
Ans: No, In this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.
19. What classes of exceptions may be caught by a catch clause?
Ans: A catch clause can catch any exception that may be assigned to the class Throwable type. This includes the Error and Exception types.
20. What class of exceptions are generated by the Java run-time system?
Ans: The Java runtime system generates RuntimeException and Error exceptions.
21. What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?
Ans: A method's throws clause must declare any checked exceptions that are not caught within the body of the method.
22. Which arithmetic operations can result in the throwing of an Arithmetic Exception?
Ans: Integer / and % can result in the throwing of an ArithmeticException.
23. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
(This question is same as unhandled exceptions)
Ans: The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
24. Can try statements be nested?
Ans: Try statements may be tested.
25. How does a try statement determine which catch clause should be used to handle an exception?
Ans: When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.
26. What is the difference between final, finalize( ) and finally ?
Ans: final: final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from sub classing a secure class to invoke insecure methods. A final method can’t be overridden and a final variable can’t change from its initialized value.
finalize( ) : finalize( ) method is used just before an object is destroyed and can be called just prior to garbage collection.
finally: finally, a key word used in exception handling, 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. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.
27. When does an Exception occur?
Ans: Whenever an error occurs in an Application, either at compile time or runtime, it raises an Exception.
28. What is throwing an Exception?
Ans: The act of passing an Exception Object to the runtime system is called throwing an Exception.
- J Madhava Rao





