Java Module-4
Java Module-4
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed
by finally block later.
finally The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the
block code will not execute.
Example 4
Here, we handle the exception using the parent class exception.
TryCatchExample4.java
public class TryCatchExample4 {
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.
TryCatchExample5.java
public class TryCatchExample5 {
}
Can't divided by zero
Example 6
Let's see an example to resolve the exception in a catch block.
TryCatchExample6.java
public class TryCatchExample6 {
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the exception code. So, enclose
exception code within a try block and use catch block only to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a
different type of exception class (ArrayIndexOutOfBoundsException).
TryCatchExample8.java
}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsExcep
tion
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 9
Let's see an example to handle another unchecked exception.
TryCatchExample9.java
public class TryCatchExample9 {
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.
TryCatchExample10.java
import java.io.FileNotFoundException;
import java.io.PrintWriter;
PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File saved successfully");
}
1. }
Output:
We can also define our own set of conditions and throw an exception explicitly
using throw keyword. For example, we can throw ArithmeticException if we
divide a number by another number. Here, we just need to set the condition and
throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
throw new exception_class("error message");
Let's see the example of throw IOException.
throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For
example, Exception is the sub class of Throwable and the user-defined
exceptions usually extend the Exception class.
The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the
exception or declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the
exception using catch block or the method must declare it using throws
declaration.
TestThrow2.java
import java.io.*;
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:
Throws:
Java throws keyword is used to declare an exception. It gives an information
to the programmer that there may occur an exception. So, it is better for the
programmer to provide the exception handling code so that the normal flow of
the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there
occurs any unchecked exception such as NullPointerException, it is
programmers' fault that he is not checking the code before it being used.
Syntax of Java throws
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
Which exception should be declared?
Ans: Checked exception only, because:
o unchecked exception: under our control so we can correct our code.
o error: beyond our control. For example, we are unable to do anything if
there occurs VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws Example
Testthrows1.java
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either
caught or declare the exception.
There are two cases:
1. Case 1: We have caught the exception i.e. we have handled the exception
using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword
with the method.
Case 1: Handle Exception Using try-catch block
In case we handle the exception, the code will be executed fine whether
exception occurs during the program or not.
Testthrows2.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Case 2: Declare Exception
o In case we declare the exception, if exception does not occur, the code
will be executed fine.
o In case we declare the exception and the exception occurs, it will be
thrown at runtime because throws does not handle the exception.
Let's see examples for both the scenario.
A) If exception does not occur
Testthrows3.java
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exce
ption
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
device operation performed
normal flow...
B) If exception occurs
Testthrows4.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exce
ption
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
4. Declaration throw is used within the throws is used with the method
method. signature.
Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any).
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a
file, closing connection, etc.
o The important statements to be printed can be placed in the finally block.
Usage of Java finally
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw any
exception, and the finally block is executed after the try block.
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
Output:
Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however
the catch block cannot handle it. Despite this, the finally block is executed after
the try block and then the program terminates abnormally.
TestFinallyBlock1.java
public class TestFinallyBlock1{
public static void main(String args[]){
try {
Output:
try {
System.out.println("Inside try block");
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if the program exits (either by
calling System.exit() or by causing a fatal error that causes the process to abort).
Rethowing exceptions:
Sometimes we may need to rethrow an exception in Java. If a catch block
cannot handle the particular exception it has caught, we can rethrow the
exception. The rethrow expression causes the originally thrown object to be
rethrown.
Because the exception has already been caught at the scope in which the
rethrow expression occurs, it is rethrown out to the next enclosing try block.
Therefore, it cannot be handled by catch blocks at the scope in which the
rethrow expression occurred. Any catch blocks for the enclosing try block have
an opportunity to catch the exception.
Syntax
catch(Exception e) {
System.out.println("An exception was thrown");
throw e;
}
Example:
public class RethrowException {
public static void test1() throws Exception {
System.out.println("The Exception in test1() method");
throw new Exception("thrown from test1() method");
}
public static void test2() throws Throwable {
try {
test1();
} catch(Exception e) {
System.out.println("Inside test2() method");
throw e;
}
}
public static void main(String[] args) throws Throwable {
try {
test2();
} catch(Exception e) {
System.out.println("Caught in main");
}
}
}
Output
The Exception in test1() method
Inside test2() method
Caught in main
Exception specification:
Built in exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of
important built-in exceptions in Java.
Examples of Built-in Exception:
1. Arithmetic exception : It is thrown when an exceptional condition has
occurred in an arithmetic operation.
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo {
public static void main(String[] args) {
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
} catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output
Can't divide a number by 0
2. ArrayIndexOutOfBounds Exception: It is thrown to indicate that an array
has been accessed with an illegal index. The index is either negative or greater
than or equal to the size of the array.
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String[] args) {
try {
int[] a = new int[5];
a[5] = 9; // accessing 6th element in an array of size 5
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output
Array Index is Out Of Bounds
}
class Navkis {
}
class MyClass {
public static void main(String[] args) {
try {
Object o = Class.forName(args[0]).newInstance();
System.out.println("Class created for " + o.getClass().getName());
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
}
}
Output:
ClassNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String[] args) {
try {
// Following file does not exist
File file = new File("file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output
File does not exist
class IOE {
public static void main(String[] args) {
try {
FileInputStream f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
}
f.close();
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}
Output:
error: unreported exception IOException; must be caught or declared to be
thrown
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or
doing some processing, and it is interrupted.
// Java Program to illustrate InterruptedException
class InterruptedException {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to
be thrown
Output:
NullPointerException..
Output:
Number format exception
10. StringIndexOutOfBoundsException : It is thrown by String class methods
to indicate that an index is either negative than the size of the string.
class StringIndexOutOfBound_Demo {
public static void main(String[] args) {
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException
class Demo
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception
class
}
else
{
System.out.println(a+b);
}
}
class Demo
{
static void find(int arr[], int item) throws ItemNotFound
{
boolean flag = false;
for (int i = 0; i < arr.length; i++) {
if(item == arr[i])
flag = true;
}
if(!flag)
{
throw new ItemNotFound("Item Not Found"); //calling constructor of user-
defined exception class
}
else
{
System.out.println("Item Found");
}
}
Output:
ItemNotFound: Item Not Found