Exception Handling
Exception Handling
LAB 5
EXCEPTION HANDLING
CONCEPTS OF EXCEPTION HANDLING
Exception is an abnormal condition that arises in the code sequence. It can be anything which
interrupts the normal flow of the program.
There can be several reasons for an exception. For example, following situations can cause an
exception:
– Opening a non-existing file, Network connection problem, Operands being manipulated are
out of prescribed ranges, class file missing which was supposed to be loaded and so on.
In the programming languages that do not support exception handling, errors must be checked
and handled manually, usually through the use of error codes.
In contrast, Java:
Provides syntactic mechanisms to signal, detect and handle errors
Ensures a clean separation between the code executed in the absence of errors and the
code to handle various kinds of errors
Brings run-time error management into object-oriented programming
In Java, exceptions are objects. When you throw an exception, you throw an object. However
-- You can't throw just any object as an exception, only those objects whose classes descend
from Throwable.
Throwable serves as the base class for an entire family of classes, declared in java.lang, that
your program can instantiate and throw.
Exceptions are thrown to signal abnormal conditions that can often be handled by some
catcher, though it's possible they may not be caught and therefore could result in a dead
thread.
Errors are usually thrown for more serious problems, such as OutOfMemoryError, that may
not be so easy to handle. They usually indicate errors with the runtime environment;
user programs are not supposed to catch them. In general, code you write should throw only
Exceptions, not Errors.
Errors are usually thrown by the methods of the Java API, or by the Java virtual machine
itself.
EXCEPTIONS AND ERRORS
Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions.
Few examples –
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
HIERARCHY OF EXCEPTION CLASSES
EXCEPTION SOURCES
Note: If a catch block handles multiple exceptions, you can separate them using a pipe (|)
EXAMPLE : 1
class Excl
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Excl.main(Excl.java:6)
Output:
Division by zero.
After catch statement.
EXAMPLE : 2
// Handle an exception and move on with the rest of the program
class HandleError
{
public static void main(String args[])
{
int a=12345, b=0;
for(int i=10; i>-5; i--)
{
try
{
b = a / i;
System.out.println(b);
}
catch (ArithmeticException e)
{
System.out.println("Division by zero."); // to print your custom message
System.out.println("Exception: " + e); // to print system generated error
message
a = 1234; // set a to 1234 and continue
}
}
System.out.println("This is continuation of the program");
}
}
EXAMPLE : 3
// Demonstrate multiple catch statements
class MultipleCatches
{
public static void main(String args[])
{
try
{
int a = args.length;
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 out of bound: " + e);
}
System.out.println("After try/catch blocks.");
}
}
>java MultipleCatches
>java MultipleCatches 5
CATCH MULTIPLE DIFFERENT EXCEPTIONS IN THE SAME CATCH BLOCK
From Java 7 it was made possible to catch multiple different exceptions in the same catch block
EXAMPLE : 4
// Demonstrate multiple catch statements, order of catch blocks
/* This program contains an error. A Sub-class must come before its Super-class in a series of catch statements. If not,
unreachable code will be created and a compile-time error will result.*/
class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) // ERROR - unreachable
{
System.out.println("This is never reached.");
}
}
}
}
catch(ArithmeticException e){
System.out.println("Divide by 0: " + e);
}
}
}
>java NestTry
>java NestTry 1
>java NestTry 1 2
THROWING EXCEPTIONS(THROW)
So far, we were only catching the exceptions that are automatically thrown by the Java
system.
A user program may throw an exception explicitly:
throw ThrowableInstance;
ThrowableInstance must be an object of type Throwable or its subclass.
Once an exception is thrown by:
throw ThrowableInstance;
1)The flow of control stops immediately.
2) The nearest enclosing try statement is inspected if it has a catch statement/block that
matches the type of exception:
If one exists, control is transferred to that block
otherwise, the next enclosing try statement is examined
If no enclosing try statement has a corresponding catch clause, the default exception handler halts
the program and prints the stack
EXAMPLE : 6
// Demonstrate use of throw
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
e.printStackTrace();
}
}
}
FINALLY CLAUSE
where exception-list is a comma-separated list of all types of exceptions that a method might
throw.
All exceptions must be listed except Error and RuntimeException or any of their subclasses,
otherwise a compile-time error occurs.
EXAMPLE : 9
// Demonstrate throws
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("Demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
(OR)
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("Demo");
}
public static void main(String args[]) throws IllegalAccessException
{
throwOne();
}
}
EXAMPLE 10: USER DEFINE EXCEPTION/ CUSTOM
EXCEPTION
A new exception class is defined, with a private variable: detail, a one parameter constructor and an
overridden toString method:
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
The static compute method throws the MyException exception whenever its a argument is greater than 10:
class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if (a > 10) throw new MyException(a);
System.out.println("Normal exit");
}
EXAMPLE-10: USER DEFINE EXCEPTION CONT..
The main method calls compute with two arguments within a try block that catches the MyException exception:
Write a Java program to find factorial of given n numbers. Read the value of n as a command line
Argument and read the n integers using Scanner class.
Throw multiple user-defined exceptions and define multiple catch statements to handle them:
NotAnIntegerException : If user gives any other input rather than integers the application
must this user defined exception.
NegativeNumberException: If the user gives a negative integer as input the application must
throw this user defined exception.
OutOfMemoryException: If the user gives an integer greater than 16 as input the application
Must throw this user defined exception.
$ java TestFactorial 5
Enter an integer:0
Factorial of 0 is: 1
Enter an integer:1
Factorial of 1 is: 1
Enter an integer:5
Factorial of 5 is: 120
Enter an integer:-4
NegativeNumberException[-4]
Enter an integer:16
Factorial of 16 is: 2004189184
Enter an integer:18
OutOfMemoryException[18]
Enter an integer:h
Not An Integer Exception
Enter an integer:7
Factorial of 7 is: 5040
End of Execution
PRE LAB QUESTIONS
1. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/module-summary.html
2. https://www.javatpoint.com/java-tutorial
3. https://www.tutorialspoint.com/java/java_documentation.htm
4. https://in.udacity.com/course/java-programming-basics--ud282
5. https://www.youtube.com/channel/UCElB8X42691dD9R6xVTDLkw
6. Herbert Schildt, The Complete Reference Java, 7th Edition, Tata McGraw Hill, 2006.