Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Chapter Six

Exceptions
6.1 Understanding Exceptions in Java
 An exception is an error that happens when an application is running.
 Exceptions are events that occur during the execution of programs that disrupt the normal flow of
instructions.
 In Java, an exception is an object that wraps an error event that occurred within a method and
contains:
 Information about the error including its type
 The state of the program when the error occurred
 Optionally, other custom information
 When an exception condition happens, the exception is said to be thrown.
 All exceptions are represented by classes organized into a hierarchy tree

6.1.1 Why we use exception


 Exceptions separate error handling code from regular code.
 Exceptions propagate errors up the call stack.
 Exception classes group and differentiate error types.( You can group errors by their generalize
parent class)
 Exceptions standardize error handling.

6.1.2 The Exception Tree in Java

 everything in Java is a class (or object)


 They are organized into a hierarchy of classes, a part of which is shown in Figure bellow

 The Throwable class, which is the root of the exceptions tree, is the base class of all the
exceptions in Java.
 The two subclasses of Throwable, directly derived from Throwable, are Error and Exception.
 Errors (represented by subclasses of Error) occur in the Java virtual machine (JVM) and not in the
application itself. Error generally represents an unusual problem from which it is difficult to
recover.
 The exceptions (represented by subclasses of Exception), on the other hand, generally originate
from within the application.it occurs do to programming error or system error.
 The exceptions should generally be handled in the program, but you are not required to handle all
of them. Some examples of exceptions are division by zero, out of boundary arrays, and file
input/output problems.
 Exception class can be grouped into two main categories: checked exceptions and unchecked
exceptions.

6.1.3 Checked exceptions vs. Unchecked exceptions


 If you perform an operation that causes an exception in your program that is,an exception is
thrown.
 You can always catch the exception (you will see how later in the chapter) and deal with it in the
code. This is called handling the exception.
 Based on whether or not you are required to handle them, the exceptions in Java are classified
into two categories: checked exceptions and Unchecked exception (Runtime exception).

Checked Exceptions:
 This is the category of exceptions for which the compiler checks to ensure that your code is
prepared for them.” prepare for unwelcome but expected guests”
 These exceptions are the instances of the Exception class or one of its subclasses, excluding the
Runtime Exception sub tree.
 Checked exceptions are generally related to how the program interacts with its environment. For
example, URISyntaxException and ClassNotFoundException are checked exceptions.
 The conditions that generate checked exceptions are generally outside the control of your
program, and hence they can occur in a correct program.
 However, you can anticipate (expect) them, and thus you must write the code to deal with them.
 The rule is: when checked exceptions are expected, either declare it in the throws clause of your
method or catch it in the body of your method, or do both.
 Note: The programmer is required to write code to deal with checked exceptions. The compiler
checks that such code exists. As opposed to the checked exceptions, the runtime exceptions are
not checked by the compiler.

Unchecked Exceptions (runtime exception)


 The exceptions of type Runtime Exception occur due to program bugs.
 The programmer is not required to provide code for these exceptions because if the programming
were done correctly in the first place, these exceptions wouldn’t occur, anyway.
 Because a runtime exception occurs as a result of incorrect code, catching the exception at
runtime is not going to help, although doing so is not illegal.
 It is better to write the correct code to avoid the runtime exceptions than write the code to catch
them.
 An exception represented by the ArithmeticException class is an example of runtime exceptions.
 Again, you do not need to declare or catch these exceptions.
 Runtime exceptions (exceptions of type RuntimeException or its subclasses) and errors (of type
Error or its subclasses) combined are also called unchecked exceptions and they are mostly
thrown by the JVM, whereas the checked exceptions are mostly thrown programmatically.
However, there is no rigid rule.
 Note: Runtime exceptions are not checked by the compiler, and you are not required to deal with
them, but it is not illegal to catch them.
Some Examples of Unchecked Exceptions in Java

6.2 Basics of Exception Handling


 You are required to handle the checked exceptions in your code, because otherwise the compiler
will generate errors.
 The Java exception-handling mechanism contains five keywords: try, catch,throw, throws, and
finally. You will explore how to use them to handle exceptions.
 You are not required to handle the unchecked exceptions, because you cannot recover from them.
However, you can use the Java exception-handling mechanism on them.
 Just for sake of convenience, we can see ArithmeticException to demonstrate the use of this
mechanism. For example, consider the following code fragment
1. int x = 15;
2. int y = 0;
3. System.out.println ("x/y: " + x/y);
4. System.out.println("x*y: " + x*y);
5. System.out.println("x-y: " + (x-y));
Notice the problem in line 3: the division by zero. This problem will cause an exception of type
ArithmeticException. But because this is a runtime exception, the code will compile without any error
from the compiler. However, at runtime, the exception would be thrown and the program would terminate
at line 3; lines 4 and 5 would never be executed.

Using the try and catch Blocks


 When your program performs an operation that causes an exception, an exception will be thrown.
You can catch that exception and handle it by using the try and catch blocks.
 As an example
1. public class ExceptionHandle1{
2. public static void main(String[] args) {
3. int x = 15;
4. int y = 0;
5. try{
6. System.out.println ("x/y: " + x/y);
7. System.out.println("x*y: " + x*y);
8. }
9. catch (ArithmeticException ae) {
10. System.out.println("An exception occurred: " + ae);
11. }
12. System.out.println("x-y: " + (x-y));
13. }
14. }

The suspected code is embraced in the try block, followed by the catch block in which the code to
handle the exception is written.

An exception of type ArithmeticException would be thrown due to line 6 (division by zero), and this
exception would be caught at line 9.The variable ae is an object reference to the instance of
ArithmeticException, and contains the message regarding the exception.

Note that the execution control jumps from line 6 directly to line 9. The execution continues after the last
catch block as if nothing happened. Therefore, the output is:

An exception occurred:java.lang.ArithmeticException / by zero


x-y: 15

If an exception is thrown from the try block and an appropriate catch block (to catch the exception) did
not exist, the method would be terminated without executing any other line from the method.
 Note: A catch block is executed only if it catches the exception coming from within the
corresponding try block.
 It is possible to have multiple catch blocks, in which case the execution control will jump to the first
line immediately following the last catch block, after executing the right (matching) catch block.
 if no exception arises from within the try block, all the catch blocks are skipped.

Using the finally Block


 If an exception is caused inside a try block, and there is no matching catch block, the method
terminates without further executing any line of code from that method.
 If you want some lines of code to be executed regardless of whether or not there is a matching catch
block, you can put those lines inside the finally block, which should follow the last catch block.
 You may need a finally block, for example, to write the cleanup code.
 Example of the code for demonstrating final block:
1. public class ExceptionHandle2{
2. public static void main(String[] args) {
3. int x = 15;
4. int y = 0;
5. try{
6. System.out.println ("x/y: " + x/y);
7. System.out.println("x*y: " + x*y);
8. } catch (ArrayIndexOutOfBoundsException oe) {
9. System.out.println("An exception occurred: " + oe);
10. }
11. finally {
12. System.out.println("finally block must be executed!");
13. }
14. System.out.println("x-y: " + (x-y));
15. }
16. }
An ArithmeticExceptionis caused by line 6, and there is no matching catch block. Therefore, the
execution control jumps to the finally block. After executing the finally block, the execution leaves
the method.
the output of the above code is :
finally block must be executed!
java.lang.ArithmeticException: / by zero…// The output truncated here.
 Note: Once execution enters a try block and an exception happens, the finally block, if one exists, is
always executed regardless of whether or not the exception is caught.
 Note: that a try block without a catch block is legal if it has a finally block, but a catch block or a
finally block without a try block is not legal; the compiler will generate an error.
Using Multiple catch Blocks:
 A catchblock catches exceptions of a specific category. This category includes the class specified in
the parentheses of catch(…), and its subclasses.
 The trade-off is to use multiple catch blocks following a single try block, followed by a single finally
block.
 When you use multiple catch statements, it is important to remember that exception subclasses must
come before any of their super classes.

e.g. ... // Compiler complains catch blocks at (1) and (2), which
catch (Exception e) { // (1) superclass will result in a compile time error:
System.out.println(e); the superclass Exception will
} catch (ArithmeticException e) { //(2) subclass shadow the subclass
System.out.println(e); ArithmeticException.
} ...

 general form of exception handling:

try { // try block

<statements> }

catch (<exception type1> <parameter1>) { // catch block

<statements> }

...

catch (<exception typen> <parametern>) { // catch block

<statements> }

finally { // finally block

<statements> }

 Example :
class ExmpleMB{
public static void main(String args[]) {
try {
int a = 0; //check it with non zero
System.out.println("a = " + a);
int b = 20/ a;
int c[] = { 2 };
c[20] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}

finally {
System.out.println(“finally always printed whether or not an exception is thrown “);
}

System.out.println("After try/catch blocks.");


}
}

The output of the above code is:


a=0
Divide by 0 ArithmeticException :divide by /0
finally always printed whether or not an exception is thrown
After try/catch blocks
But if the value of “a” non-zero let it is 3 the output is
a=3
Array index oob
finally always printed whether or not an exception is thrown
After try/catch blocks.
Example 2:try it in you lab class to see the output by changing the value

public class FinallyBExample{

public static void main(String args[]){


try{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=20/a;
int c[]={3};
c[5]=8;
} catch(ArithmeticException e) {
System.err.println(“exception”+e);
} catch(ArrayIndexOutOfBoundsException e) {
System.err.println("Array index oob: " + e);
}catch(InputMismatchException ime){
System.err.println(“input mismatch exception: " + e);
}finally {
System.out.println(“always printed whether or not an exception is thrown “);
}
}
}

You might also like