1.exceptions in Java
1.exceptions in Java
Exceptions in Java
• An exception is an event, which occurs during the execution
of a program, that disrupts the normal flow of the program's
instructions.
Checked Exception
• These are the exceptions that are checked at compile time. If
some code within a method throws a checked exception, then
the method must either handle the exception or it must
specify the exception using throws keyword.
• Checked Exceptions are those, that have to be either caught
or declared to be thrown in the method in which they are
raised.
• Examples: FileNotFoundException, IOException,
SQLException, ClassNotFoundException
Example in the next slide:
.
Checked Exception
import java.io.*;
public class checked {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\Users\\abc\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
The program doesn’t compile, because the function main() uses FileReader()
and FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw checked
exception IOException
Method throwing Checked Exception
import java.io.*;
public class checkedcorrect {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\Users\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
We have used throws in the below program. Since FileNotFoundException is a subclass
of IOException, we can just specify IOException in the throws list and make the above program
compiler-error-free.
Output:
<First three lines a.txt will be printed>
Java’s Checked Exceptions defined in java.lang package
IOException
SQLException
FileNotFoundException[Sub-class of IOException]
Unchecked Exceptions
try
• used to execute the statements whose execution may result in
an exception.
try {
Statements whose execution may cause an exception
}
Note: try block is always used either with catch or finally or with
both.
catch
• catch is used to define a handler.
at Main.main(Main.java:7)
Internal working of java try catch block
Multiple catch clauses
• In some cases, more than one exception could be raised by a
single piece of code.
• To handle this type of situation, you can specify two or more
catch clauses, each catching a different type of exception.
When an exception is thrown, each catch statement is
inspected in order, and the first one whose type matches that
of the exception is executed.
• After one catch statement executes, the others are bypassed,
and execution continues after the try /catch block.
• At a time only one exception occurs and at a time only one
catch block is executed.
• All catch blocks must be ordered from most specific to most
general, Example: catch for ArithmeticException must come
before catch for Exception.
Example
public class Main {
public static void main(String[] args) {
try{
String x="ABC";
int a[]=new int[5];
a[0]=30/0;//It will raise ArithmeticException
//System.out.println(a[7]);//It will raise ArrayIndexOutOfBoundsException
//System.out.println(Integer.parseInt(x));//It can raise NumberFormatException, but its specific catch is not
written so catch with Exception class will work
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Multi-catch feature introduced from JDK 7 onwards
// Demonstrate the multi-catch feature.
public class Main {
public static void main(String args[]) {
int a=10, b=0;
int vals[] = { 1, 2, 3 };
try {
int result = a / b; // generate an ArithmeticException
//vals[10] = 19; // generate an ArrayIndexOutOfBoundsException
// This catch clause catches both exceptions.
} catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
System.out.println("After multi-catch.");
}
}
Output:
Exception caught: java.lang.ArithmeticException: / by zero
After multi-catch.
Example, where compilation error could come
public class Main {
public static void main(String[] args) {
try{
String x="ABC";
int a[]=new int[5];
a[0]=30/0;//It will raise ArithmeticException
//System.out.println(a[7]);//It will raise ArrayIndexOutOfBoundsException
//System.out.println(Integer.parseInt(x));//It can raise NumberFormatException, but its
specific catch is not written so catch with Exception class will work
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
System.out.println("rest of the code");
}
}
Here compilation error will come, as general catch handler with super class is written first and
then the subclass catches are written
Nested try statements
• The try block within a try block is known as nested try block in java.
• Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Example
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e+" inner");}
System.out.println(arr[6]);
}catch(Exception e){System.out.println(e+" outer");}
System.out.println("After try catch");
}
}
Output:
going to divide
java.lang.ArithmeticException: / by zero inner
java.lang.ArrayIndexOutOfBoundsException: 5 inner
java.lang.ArrayIndexOutOfBoundsException: 6 outer
After try catch
Defining Generalized Exception Handler
import java.io.*;
public class abc {
public static void findFile() throws IOException {
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e){
System.out.println(e);
}
}
}
Output:
java.io.FileNotFoundException: test.txt (No such file or directory)
throw vs throws
No. throw throws
3) Throw is used within the method. Throws is used with the method
signature.
4) You cannot throw multiple exceptions. You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.
Finally
• finally creates a block of code that will be executed after a
try/catch block has completed and before the code following the
try/catch block.
procC's finally
Propagation of Exceptions
If we use try catch block to handle the exceptions then code will be executed even after the exception is
thrown which is not possible without handling the exception. If we do not handle the exception then JVM
will give built in exception message and terminate the program.
NullPointerException
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
ArrayIndexOutOfBounds Exception
Output:
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
at Main.main(Main.java:8)
/ by zero
Example 2
public class Main
{
public static void main(String[] args) {
try
{
throw new ArithmeticException("Wrong denominator");
}
catch(ArithmeticException e)
{
System.out.println(e);
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Output:
java.lang.ArithmeticException: Wrong denominator
java.lang.ArithmeticException: Wrong denominator
at Main.main(Main.java:7)
Wrong denominator
Example 3
public class Main
{
public static void main(String[] args) {
try
{
throw new ArithmeticException();
}
catch(ArithmeticException e)
{
System.out.println(e);
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Output:
java.lang.ArithmeticException
java.lang.ArithmeticException
at Main.main(Main.java:7)
null
Q1
Predict the output of following Java program
public class Main {
public static void main(String args[]) {
try {
throw 10;
}
catch(int e) {
System.out.println("Got the Exception " + e);
}
}
}
A. Got the Exception 10
B. Got the Exception 0
C. Compiler Error
D. Blank output
Q2:What will be the output of following code?
catch(ArithmeticException e)
{
System.out.println ("Divide by zero error");
}
finally
{
System.out.println ("inside the finally block");
}
}
}
A. Compile error
B. Divide by zero error
C. a = 0
Divide by zero error
inside the finally block
D. a = 0
What will be the output of following code?[Q5]
public class Test
{
public static void main(String[] args)
{
try
{
int a[]= {1, 2, 3, 4};
for (int i = 1; i <= 4; i++)
{
System.out.println ("a[" + i + "]=" + a[i] + "n");
}
}
catch (Exception e)
{
System.out.println ("error = " + e);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("ArrayIndexOutOfBoundsException");
}
}
}
A. Compiler error
B. Run time error
C. ArrayIndexOutOfBoundsException
D. Array elements are printed
Predict the output of the following program.[Q6]
public class Test void display()
{ int count = 0; {
void A() throws Exception
{ System.out.println(count);
try }
{
count++;
public static void main(String[] args) throws
try Exception
{ {
count++;
Test obj = new Test();
try obj.A();
{ obj.display();
count++;
throw new Exception(); }
} }
catch(Exception ex)
{
A. 4
count++; B. 5
throw new Exception(); C. 6
}
} D. Compilation error
catch(Exception ex)
{
count++;
}
}
catch(Exception ex)
{
count++;
}
}
Which of these is a super class of all errors and
exceptions in the Java language?[Q7]
A. RunTimeExceptions
B. Throwable
C. Catchable
D. None of the above
public class Test Output??[Q8]
{
public static void main(String[] args)
{
try
{
System.out.printf("1");
int sum = 9 / 0;
System.out.printf("2");
}
catch(ArithmeticException e)
{
System.out.printf("3");
}
catch(Exception e)
{
System.out.printf("4");
}
finally
{
System.out.printf("5");
}
}
}
a) 1325
b) 1345
c) 1342
d) 135
Output??[Q9]