Chapter9 ExceptionHandling
Chapter9 ExceptionHandling
Syntax errors such as spelling mistakes, which will be reported to users while
compiling the program using javac compiler.
E.g. 1. Missing semicolon
2. Using keyword as variable name
3. Using “;” after the function definition
4. Improperly matched parentheses, square brackets, and curly
braces etc.
Logical errors or Semantic error such as a mistake in the logic of the program.
These errors will not be reported during compile and run time. However we will
not get the desired output from the program.
E.g. 1. Multiplying when you should be dividing
2. Adding when you should be subtracting
3. Using assignment operator instead of equality operator
In Java, runtime errors are represented as exceptions.
What really matters is "what happens after an abnormality occurred?" In other words,
"how the abnormal situations are handled by your program." If these exceptions are not
handled properly, the program terminates abruptly and may cause severe consequences.
Java has a built-in mechanism for handling runtime errors, referred to as exception
handling.
For example, if you have declared an array of size 5 in your program, and trying to call
the 6th element of the array then an ArrayIndexOutOfBoundsException occurs.
Example
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following exception.
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Errors − These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error will
arise. They are also ignored at the time of compilation.
Try-catch-finally Statements
// SimpleException.java
public class SimpleException
{
public static void main(String args[])
{
int a = 20;
int b = 0;
int value = a/b;
System.out.println(“value: ” + value);
}
}
Output
Exception in thread “main” java.lang.ArithmeticException: / by zero
at SimpleException.main(SimpleException.java:7)
In this application, the println() statement displaying value will not be executed because
in the previous line, the integer division by zero is not allowed and it will raise an
exception, thereby the program terminates. So, we need to instruct the application what
is to be done when division by zero occurs. This process is known as exception
handling.
Exception handling is a process of identifying possible runtime errors that are likely to
happen and handle or solve this exception so that normal execution will continue.
try
{
// statements that will possibly throw one or more exceptions
}
catch(exception-type 1)
{
// handling code for exception-type1
}
catch(exception-type n)
{
// handling code for exception-type n.
}
finally
{
// statements to be executed after try block or catch block
}
Try block will contain statements that are likely to throw exceptions. If an exception has
occurred, control is transferred to any one of the catch blocks. Catch block will contain
statements that can solve this exception. Then execution will continue with
finally block. Remember, finally block will be executed irrespective of exceptions. Also,
there can be any number of catch blocks for the given single try block
The application depicted Int() method unable to convert string into int, may supply a
zero for second number that causes division by zero and intentionally we try to access
an array location outside its size.
// ExceptionTest. java
import java.io.*;
import java.util.*;
public class ExceptionTest
{
public static void main(String[] args)
{
try
{
int a = Integer.parseInt(args[0]); // user may enter other than int
int b = Integer.parseInt(args[1]); // user may enter other than int
int sum = a / b; // infinity may happen if b is zero
Output
C:\jdk>java ExceptionTest 10 20.o
Please type only integers for a and b
Think of all possible exceptions while designing your code
C:\jdk>java ExceptionTest 10 0
Trying to divide by zero, ensure nonzero for b
Think of all possible exceptions while designing your code
C:\jdk>java ExceptionTest 10 20
Trying to access outside array index
Think of all possible exceptions while designing your code
When parseInt() is unable to convert, then control is transferred to catch block of
NumberFormat Exception. When division by zero occurs, then control goes to catch
block with ArithmeticException. Also, when array[2] is accessed, then control goes to
the third catch block where ArrayIndexOut ofBoundsException is handled.
Multicatch Statement
In Java 7, it is possible to catch multiple different exceptions in the same catch block.
This is also known as multicatch statement and is created using pipe character.
// MultiCatch.java
import java.io.*;
public class MultiCatch
{
public static void main(String[] args)
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a / b;
}
catch(NumberFormatException | ArithmeticException e )
{
System.out.println(“Enter only nonzero integers for a and b”);
}
}
}
Output
C:\jdk>java MultiCatch 10 20
C:\jdk>java MultiCatch 10 20.0
Enter only nonzero integers for a and b
C:\jdk>java MultiCatch 10 0
Enter only nonzero integers for a and b
Exception Hierarchy
Java developer can create their own exception class by extending Exception or
RuntimeException class. In order to display meaningful information about the exception,
toString() method can be overridden inside the user-defined exception class.
The throw statement can be used to create an object of user-defined exception and
used inside try-catch block. For example, a school wants to check the age of a kid for
possible admission to its kinder garden programme
//UnderAgeExceptionTest.java
import java.util.*;
class UnderAgeException extends Exception
{
private int age;
public UnderAgeException(int a)
{
age = a;
}
public String toString()
{
return age + “ year is under age for Kinder Garden” + “\nPlease come next
year for admission! ”;
}
}
public class UnderAgeExceptionTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“What is your kid’s age ?: ”);
int age = sc.nextInt();
try
{
if (age < 2)
throw new UnderAgeException(age);
else
System.out.print(“Your child will be admitted to Kinder
Garden in our school”);
}
catch(UnderAgeException e)
{
System.out.println(e.toString());
}
}
}
Output
What is your kid’s age ?: 2
Your child will be admitted to Kinder Garden in our school
What is your kid’s age ?: 1
1 year is under age for admission to Kinder Garden
A method can use throws statement to indicate that it might throw the exception back to
the caller, so that the caller can catch this exception and take appropriate action. The
next program is a revised school admission application where checkAge() method may
throw UnderAgeException exception.
//UnderAgeExceptionTest1.java
import java.util.*;
public class UnderAgeExceptionTest1
{
public void checkAge(int age) throws UnderAgeException
{
if (age < 2)
throw new UnderAgeException(age);
else
System.out.print(“Your child will be admitted to Kinder Garden in
our school”);
}
public static void main(String[] args)
{
UnderAgeExceptionTest1 u = new UnderAgeExceptionTest1();
Scanner sc = new Scanner(System.in);
System.out.print(“What is your kid’s age ?: ”);
int age = sc.nextInt();
try
{
u.checkAge(age);
}
catch(UnderAgeException e)
{
System.out.println(e.toString());
}
}
}
Output
What is your kid’s age ?: 2
Your child will be admitted to Kinder Garden in our school
What is your kid’s age ?: 1
1 year is under age for admission to Kinder Garden
Please come next year for admission!