ZeePedia

JAVA: Intro to Exceptions

<< JAVA: Collections
JAVA: Streams >>
img
Web Design & Development ­ CS506
VU
Lesson 7
Intro to Exceptions
Types of Errors
Generally, you can come across three types of errors while developing software. These are Syntax,
Logic & Runtime errors.
1. Syntax Errors
Arise because the rules of the language are not followed.
2. Logic Errors
Indicates that logic used for coding doesn't produce expected output.
3. Runtime Errors
Occur because the program tries to perform an operation that is impossible to complete.
Cause exceptions and may be handled at runtime (while you are running the program)
For example divide by zero
What is an Exception?
An exception is an event that usually signals an erroneous situation at run time
Exceptions are wrapped up as objects
A program can deal with an exception in one of three ways:
o
ignore it
o
handle it where it occurs
o
handle it an another place in the program
Why handle Exceptions?
Helps to separate error handling code from main logic (the normal code you write) of the program.
As different sort/type of exceptions can arise, by handling exceptions we can distinguish
between them and write appropriate handling code for each type for example we can
differently handle exceptions that occur due to division by Zero and exceptions that occur due to
non-availability of a file.
If not handled properly, program might terminate.
Exceptions in Java
An exception in java is represented as an object that's created when an abnormal situation
arises in the program. Note that an error is also represented as an object in Java, but usually
represents an unrecoverable situation and should not be caught
48
img
Web Design & Development ­ CS506
VU
The exception object stores information about the nature of the problem. For example,
due to network problem or class not found etc.
All exceptions in java are inherited from a class know as Throwable.
Exception Hierarchy
Following diagram is an abridged version of Exception class hierarchy
Types of Exceptions
Exceptions can be broadly categorized into two types, Unchecked & Checked Exceptions.
Unchecked Exceptions
·
Subclasses of RuntimeException and Error.
·
Does not require explicit handling
·
Run-time errors are internal to your program, so you can get rid of them by debugging
your code
·
For example, null pointer exception; index out of bounds exception; division by zero
exception; ...
Checked Exceptions
·
Must be caught or declared in a throws clause
·
Compile will issue an error if not handled appropriately
·
Subclasses of Exception other than subclasses of RuntimeException.
49
img
Web Design & Development ­ CS506
VU
·
Other arrive from external factors, and cannot be solved by debugging
·
Communication from an external resource ­ e.g. a file server or database
How Java handles Exceptions
Java handles exceptions via 5 keywords. try, catch, finally, throw & throws.
try block
·
Write code inside this block which could generate errors
catch block
·
Code inside this block is used for exception handling
·
When the exception is raised from try block, only than catch block would execute.
finally block
·
This block always executes whether exception occurs or not.
·
Write clean up code here, like resources (connection with file or database) that are
opened may need to be closed.
The basic structure of using try ­ catch ­ finally block is shown in the picture below:
try
//try block
{
// write code that could generate exceptions
} catch (<exception to be caught>)
//catch block
{
//write code for exception handling
catch (<exception to be caught>)
//catch block
{
//code for exception handling
} finally
//finally block
{
//any clean-up code, release the acquired resources
}
throw
·
To manually throw an exception, keyword throw is used.
Note: we are not covering throw clause in this handout
throws
·
If method is not interested in handling the exception than it can throw back the exception
to the caller method using throws keyword.
50
img
Web Design & Development ­ CS506
VU
·
Any exception that is thrown out of a method must be specified as such by a
throws clause.
References:
Java tutorial by Sun: http://java.sun.com/docs/books/turorial
Beginning Java2 by Ivor Hortan
Thinking in Java by Bruce Eckle
CS193j Stanford University
Code Examples of Exception Handling
Unchecked Exceptions
Example Code: UcException.java
The following program takes one command line argument and prints it on the console
// File UcException.java
public class UcException {
public static void main (String args[ ]) {
System.out.println(args[0]);
}
}
Compile & Execute
If we compile & execute the above program without passing any command line argument, an
ArrayIndexOutOfBoundsException would be thrown. This is shown in the following picture
Why?
Since we have passed no argument, therefore the size of String args[ ] is zero, and we have tried to access
the first element (first element has index zero) of this array.
From the output window, you can find out, which code line causes the exception to be raised. In the
above example, it is
51
img
Web Design & Development ­ CS506
VU
System.out.println(args[0]);
Modify UcException.java
Though it is not mandatory to handle unchecked exceptions we can still handle
Unchecked Exceptions if we want to. These modifications are shown in bold.
// File UcException.java
public class UcException {
public static void main (String args[ ]) {
try {
System.out.println(args[0]);
catch (IndexOutOfBoundsExceptoin ex) {
System.out.println("You forget to pass command line argument");
}
}
The possible exception that can be thrown is IndexOutOfBoundsException, so we handle it in the
catch block.
When an exception occurs, such as IndexOutOfBoundsException in this case, then an object  of
type IndexOutOfBoundesException is created and it is passed to the corresponding catch
block (i.e. the catch block which is capable of handling this exception). The catch block receives
the exception object inside a variable which is ex in this case. It can be any name; it is similar to
the parameter declared in the method signature. It receives the object of exception type
(IndexOutOfBoundsExceptoin) it is declared.
Compile & Execute
If we execute the modified program by passing command line argument, the program would display
on console the provided argument. After that if we execute this program again without passing
command line argument, this time information message would be displayed which is written inside
catch block.
Checked Exceptions
Example Code: CException.java
52
img
Web Design & Development ­ CS506
VU
The following program reads a line (hello world) from a file and prints it on the console. The File
reading code is probably new for you. We'll explain it in the coming handouts
(Streams). For now, assumed that the code written inside the main read one line from a file and
prints that to console.
// File CException.java
import java.io.* ;
public class CException {
public static void main (String args[ ]) {
FileReader fr = new FileReader ("input.txt");
BufferedReader br = new BufferedReader (fr);
//read the line form file
String line = br.readLine();
System.out.println(line);
}
}
Compile & Execute
If you try to compile this program, the program will not compile successfully and displays the
message of unreported exception. This happens when there is code that can generate a checked
exception but you have not handled that exception. Remember checked exceptions are detected
by compiler. As we early discussed, without handling Checked exception, out program won't compile.
Modify CException.java
As we have discussed earlier, it is mandatory to handle checked exceptions. In order to compile the
code above, we modify the above program so that file reading code is placed inside a try block. The
expected exception (IOException) that can be raised is caught in catch block.
// File CException.java
53
img
Web Design & Development ­ CS506
VU
import java.io.* ;
public class CException {
public static void main (String args[ ]) {
try{
FileReader fr = new FileReader ("input.txt");
BufferedReader br = new BufferedReader (fr);
//read the line form file
String line = br.readLine();
System.out.println(line);
catch( IOExceptoin ex) {
System.out.println(ex);
}
}
}
The code line written inside the catch block will print the exception name on the console if exception
occurs
Compile & Execute
After making changes to your program, it would compile successfully. On executing this program, hello
world would be displayed on the console
Note: Before executing, make sure that a text file named input.txt must be placed in the same
directory where the program is saved. Also write hello world in that file before saving it.
The finally block
The finally block always executes regardless of exception is raised or not while as you remembered
the catch block only executes when an exception is raised.
54
img
Web Design & Development ­ CS506
VU
Exampel Code : FBlockDemo.java
// File FBlockDemo.java
import java.io.* ;
public class FBlockDemo {
public static void main (String args[ ]) {
try{
FileReader fr = new FileReader ("strings.txt");
BufferedReader br = new BufferedReader (fr);
//read the line form file
String line = br.readLine();
System.out.println(line);
catch( IOExceptoin ex) {
System.out.println(ex);
}
finally {
System.out.println("finally block always execute");
}
}
}
Compile & Execute
The program above, will read one line from string.txt file. If string.tx is not present in the same directory
the FileNotFoundException would be raised and catch block would execute as well as the finally block.
55
img
Web Design & Development ­ CS506
VU
If string.txt is present there, no such exception would be raised but still finally block executes. This
is shown in the following output diagram
Multiple catch blocks
·
Possible to have multiple catch clauses for a single try statement
­
Essentially checking for different types of exceptions that may happen
·
Evaluated in the order of the code
­
Bear in mind the Exception hierarchy when writing multiple catch clauses!
­
If you catch Exception first and then IOException, the IOException will never be caught!
Example code: MCatchDemo.java
The following program would read a number form a file numbers.txt and than prints its square on the
console
// File MCatchDemo.java
import java.io.* ;
public class MCatchDemo {
public static void main (String args[ ]) {
try{
// can throw FileNotFound or IOException
FileReader fr = new FileReader ("numbers.txt");
BufferedReader br = new BufferedReader (fr);
//read the number form file
String s = br.readLine();
//may throws NumberFormatException, if s is not a no.
56
img
Web Design & Development ­ CS506
VU
int number = Integer.parseInt(s);
System.out.println(number * number);
catch( NumberFormatExceptoin nfEx) {
System.out.println(nfEx);
}
catch( FileNotFoundExceptoin fnfEx) {
System.out.println(fnfEx);
}
catch( IOExceptoin ioEx) {
System.out.println(ioEx);
}
}
}
We read everything from a file (numbers, floating values or text) as a String. That's why we first
convert it to number and than print its square on console.
Compile & Execute
If file numbers.txt is not present in the same directory, the FileNotFoundException
would be thrown during execution.
If numbers.txt present in the same directory and contains a number, than hopefully no exception
would be thrown.
57
img
Web Design & Development ­ CS506
VU
The throws clause
The following code examples will introduce you with writing & using throws clause.
Example Code: ThrowsDemo.java
The ThrowsDemo.java contains two methods namely method1 & method2 and one main method. The
main method will make call to method1 and than method1 will call method2. The method2 contains
the file reading code. The program looks like one given below
// File ThrowsDemo.java
import java.io.* ;
public class ThrowsDemo {
// contains file reading code
public static void method2( ) {
try{
FileReader fr = new FileReader ("strings.txt");
BufferedReader br = new BufferedReader (fr);
//read the line form file
String s = br.readLine();
System.out.println(s);
catch( IOExceptoin ioEx) {
ioEx.printStackTrace();
}
}// end method 2
//only calling method2
public static void method1( ) {
method2();
}
public static void main (String args[ ]) {
ThrowsDemo.method1();
}
}
printStackTrace method
Defined in the Throwable class ­ superclass of Exception & Error classes
58
img
Web Design & Development ­ CS506
VU
Shows you the full method calling history with line numbers.
Extremely useful in debugging
Modify: ThrowsDemo.java
Let method2 doesn't want to handle exception by itself, so it throws the exception to the caller of
method2 i.e. method1
So method1 either have to handle the incoming exception or it can re-throw it to its caller i.e. main.
Let method1 is handling the exception, so method1& method2 would be modified as:
// File ThrowsDemo.java
import java.io.* ;
public class ThrowsDemo {
// contains file reading code
public static void method2( ) throws IOEception{
FileReader fr = new FileReader ("strings.txt");
BufferedReader br = new BufferedReader (fr);
//read the line form file
String s = br.readLine();
System.out.println(s);
}// end method 2
// calling method2 & handling incoming exception
public static void method1( ) {
try {
method2();
catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
public static void main (String args[ ]) {
ThrowsDemo.method1();
}
}
59
img
Web Design & Development ­ CS506
VU
Compile & Execute
If file strings.txt is not present in the same directory, method2 will throw an exception that would be
caught by method1 and the printStackTrace method will print the full calling history on console. The
above scenario is shown in the output below:
If file strings.txt exist there, than hopefully line would be displayed on the console.
Reference
Example code, their explanations and corresponding figures for this handout are taken from the book
JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the
course Web Design and Development and not for any other commercial purpose without the consent of
author.
60