Exceptions and Error Handling
Introduction:
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, or pass it on. Either way, 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 your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. 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.
Exception-Throwing Methods:
Runtime errors appear in Java as exceptions, exception is a special type of classes that could be thrown to indicate a runtime error and provide additional data about that error. If a method is declared to throw an exception, any other method calls it should deal with this exception by throwing it (if it appears) or handle it. Recalling reading from user using BufferedReader class, we used to declare main method from which we call readLine() using throws IOException, this because readLine() is declared to throw that exception.
import java.io.*; class ReadFromUser{
public static void main(String[] args) throws IOException{
}
}
If we wish to write a method that simplifies reading from user, you may want to declare it to throw IOException.
import java.io.*; class ReadFromUser{
public static void main(String[] args) throws IOException{ String in = read(“Enter your name: “);
}
public static String read(String message) throws IOException{ System.out.print(message);
BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String input = in.readLine();
return input;
}
}
In the previous code, if an exception occurs in readLine() method, this exception is thrown as it is to read method, which originally called it, because this last one is also declared to throw that exception, it also throws it as it is to main method, which originally called it, finally, the exception is throws to JVM which prints it out on the screen so the user can know there was error.
try-catch Exception Handling:
Another technique for handling runtime errors is to use try-catch block to handle different types of exceptions and take appropriate action instead of throwing them to the user. The format of try-catch block is the following.
try{
//Statement(s) that may throw exceptions
}catch(Exception e){
//Statement(s) to handle exception.
}
For example, we can place readLine() method which throws IOException in a try-catch block as the following.
BufferedReader in = new BufferedReader new InputStreamReader(System.in)); String input;
try{
input = in.readLine();
}catch(IOException e){ System.out.println(“Error occurred”);
}
When we are expecting more than one exception, we can use several catch blocks, each one for different type of exceptions. For example, when reading a string using BufferedReader and converting it to integer, you can expect two different exceptions: IOException and NumberFormatException which occurs when the provided string cannot be converted to integer.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String input;
try{
input = in.readLine();
int x = Integer.parseInt(input);
}catch(IOException e){ System.out.println(“Error reading input”);
}catch(NumberFormatException err){ System.out.println(“This is not a valid number”);
}
Finally:
You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method. Here is how a finally clause looks:
public void openFile(){ FileReader reader = null;
try {
reader = new FileReader(“someFile”); int i=0;
while(i != -1){
i = reader.read(); System.out.println((char) i );
}
} catch (IOException e) {
//do something clever with the exception
} finally {
if(reader != null){ try {
reader.close();
} catch (IOException e) {
//do something clever with the exception
}
}
System.out.println(“— File End —“);
}
}
No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed. The example above shows how the file reader is always closed, regardless of the program flow inside the try or catch block.
Note: If an exception is thrown inside a finally block, and it is not caught, then that finally block is interrupted just like the try-block and catch-block is. That is why the previous example had the reader.close() method call in the finally block wrapped in a try-catch block:
finally {
if(reader != null){ try {
reader.close();
} catch (IOException e) {
//do something clever with the exception
}
}
System.out.println(“— File End —“);
}
Lab Activities:
Activity 1:
The example below shows the procedure for catching IndexOutOfBounds and InputMismatch exception.
Solution:
importjava.util.InputMismatchException; importjava.util.Scanner;
public class Marks {
public static void main(String args[]){ Scanner s=new Scanner(System.in); try{
int[] marks = new int[5]; for(inti=0;i<=5;i++){
System.out.println(“Enter marks for “+i+”st subjects :”); marks[i]=s.nextInt();
}
}
catch(InputMismatchException h){ System.out.println(“Please enter correct number!”);
}
catch(ArrayIndexOutOfBoundsException e){ System.out.println(“The error is”+e);
}
}
}
Activity 2:
The example below shows the procedure for using throw keyword.
Solution:
public class Exceptionclass
{
public static void main(String args[]){ try{
throw new Exception();
}
catch(Exception e){
System.out.println(“Error!!!”);
}
}
}
Activity 3:
In some cases while developing our own applications, we need to specify custom types of exceptions to handle custom errors that may occur during program execution. A custom exception is a class that inherits Exception class or any of its subclasses, since inheritance is
beyond the scope of this course, we will define it as using extends Exception in class declaration.
Solution:
class MyCustomException extends Exception{
private String message;
public MyCustomException(String message){ this.message = message;
}
public String toString(){ return message;
}
}
To use your custom exception, declare an object of it and throw that object using throw keyword. It is optional to declare the method containing throw statement with throws keyword. In the following example, the program reads student id, this id should be of length 7 and consists only of digits, otherwise it throws an exception.
class InvalidIDException extends Exception{
private String message;
public InvalidIDException(String message){ this.message = message;
}
public String toString(){ return message;
}
}
Import javax.swing.*; class StudentsData{
public static void main(String[] args){ String id, name;
name = JOptionPane.showInputDialog(“Enter student name”); id = JOptionPane.showInputDialog(“Enter student ID”);
try{
verfyID(id);
}
catch(InvalidIDException e){ JoptionPane.showMessageDialog(null, e.toString());
}
}
public static void verifyID(String id)
throws InvalidIDException{ if(id.length() != 7){
throw new InvalidIDException(“Check ID length”);
}
try{
Long.parseLong(id);
}
catch(Exception err){ throw
new InvalidIDException(“ID can contain only digits”);
}
}
}
Activity 4:
The example below shows the procedure for using throws keyword.
Solution:
//The following class represents the exception to be thrown: public class illegalamount extends Exception {
public illegalamount(){ super();
}
public illegalamount(String a){ super(a);
}
}
//Account Class’ methods deposit and withdraw will throw an exception of type illegalamount if the amount variable is not in the valid range.
public class Account {
private double balance; public Account()
{
balance = 0;
}
public Account( double initialDeposit)
{
balance = initialDeposit;
}
public double getBalance()
{
return balance;
}
public double deposit( double amount)throws illegalamount{
if (amount > 0){ balance += amount;}
else{
}
throw new illegalamount(“error in deposit”);
return balance;
}
public double withdraw(double amount) throws illegalamount
{
if ((amount > balance) || (amount < 0)){ balance -= amount;}
else{
}
throw new illegalamount(“error in withdraw”);
return balance;
}
}
Home Activities:
Activity 1:
Create a new Java file and:
- Create an exception class named NegativeNumberException extended from the class This class should contain a parameterless constructor to call the Exception class constructor with the message ―You should enter a positive number‖.
- Create a class named exercise3 that contains:
- A method named M1 that accepts a double variable as argument and returns its square The method should throw the NegativeNumberException exception defined above.
- The main method to prompt the user to enter a number and then to call the method M1 (insert a try-catch block to handle the NegativeNumberException exception)
Activity 2:
Write a program that calculates the average of N integers. The program should prompt the user to enter the value for N and then afterward must enter all N numbers. If the user enters a negative value for N, then an exception should be thrown (and caught) with the message ― N must be positive.‖ If there is any exception as the user is entering the N numbers, an error message should be displayed, and the user prompted to enter the number again.
Lab Assignment and Viva voce:
Task 1:
Write a Java program to:
- Read a number from the keyboard.
- Write a try-throw-catch bloc to calculate the square root of the entered number. An exception should be handled if the entered number is negative. Use the Exception
Task 2:
Write a program that:
- Create an exception class named AgeOutOfRangeException extended from the class This class should contain a constructor with no parameter to call the Exception class constructor with the message ―You are older than the requested age (25 years)‖.
- Create an exception class named LowGpaException extended from the class This class should contain a constructor with no parameter to call the Exception class constructor with the message ―Your GPA is not sufficient to apply for this job (2.5)‖.
- Create a main class to prompt the user to enter his/her age and his GPA. The user application for a job will be rejected either if his age is greater than 25 years or his GPA is less than 2.5. You should declare two nested try-throw-catch blocks; one to handle the AgeOutOfRangeException and the other to handle the LowGpaException. If the user enters acceptable age and GPA, display the message ―Your application is accepted and is under study‖.