You are on page 1of 28

Acharya MCA

Unit-4

Introduction

 An exception is an event that occurs during the execution of a program that disrupts
the normal flow of instruction.
o Or
 An abnormal condition that disrupts Normal program flow.
 There are many cases where abnormal conditions happen during program execution,
such as
o Trying to access an out - of –bounds array elements.
o The file you try to open may not exist.
o The file we want to load may be missing or in the wrong format.
o The other end of your network connection may be non –existence.
 If these cases are not prevented or at least handled properly, either the program will
be aborted abruptly, or the incorrect results or status will be produced.
 When an error occurs within the java method, the method creates an exception
object and hands it off to the runtime system.
 The exception object contains information about the exception including its type and
the state of the program when the error occurred. The runtime system is then
responsible for finding some code to handle the error.
 In java creating an exception object and handling it to the runtime system is
called throwing an exception.
 Exception is an object that is describes an exceptional (i.e. error) condition that
has occurred in a piece of code at run time.
 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.
 System generated exceptions are automatically thrown by the Java runtime system

Acharya MCA
Acharya MCA

Java Exception hierarchy


Here is a simplified diagram of the exception hierarchy in Java.

As you can see from the image above, the Throwable class is the root class in the hierarchy.
Note that the hierarchy splits into two branches: Error and Exception.
There are some important methods available in the Throwable class which are as follows:

 public String getMessage() – Provides information about the exception that has occurred through a
message, which is initialized in the Throwable constructor.
 public Throwable getCause() – Provides root cause of the exception as represented by a Throwable
object.
 public void printStackTrace() – Used to display the output of toString() along with the stack trace
to System.err (error output stream).

Acharya MCA
Acharya MCA

 public StackTraceElement [] getStackTrace() – Returns an array with each element present on the
stack trace. The index 0 element will symbolize the top of the call stack, and the last element of array
will identify the bottom of the call stack.

Errors (caused due to system resources):


Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors
are usually beyond the control of the programmer and we should not try to handle errors (not
recoverable).
Exceptions (caused by program):
Exceptions can be caught and handled by the program. Exceptions are recoverable. When an
exception occurs within a method, it creates an object. This object is called the exception object.
It contains information about the exception such as the name and description of the exception and
state of the program when the exception occurred.
Java Exception Types
The exception hierarchy also has two
branches: RuntimeException and IOException.
1. RuntimeException
A runtime exception happens due to a programming error. They are also known as unchecked
exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime
exceptions are:
 Improper use of an API - IllegalArgumentException
 Null pointer access (missing the initialization of a variable) - NullPointerException
 Out-of-bounds array access - ArrayIndexOutOfBoundsException
 Dividing a number by 0 - ArithmeticException
 The NullPointerException would not have occurred if you had checked whether the
variable was initialized or not before using it.
 An ArrayIndexOutOfBoundsException would not have occurred if you tested the
array index against the array bounds.

2. IOException
An IOException is also known as a checked exception. They are checked by the compiler at the
compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
 Trying to open a file that doesn’t exist results in FileNotFoundException
 Trying to read past the end of a file

Java Exception Handling


Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Benefits Of Exception Handling
1. Ensures the Continuity of the Program
One of the key benefits of exception handling is that it ensures the continuity of the program.
Without proper exception handling, an unhandled exception would cause the program to terminate

Acharya MCA
Acharya MCA

abruptly, which can lead to data loss & other issues. With proper exception handling, the program
can continue to execute and provide a more stable user experience.
2. Enhances the Robustness of the Program
Exception handling allows for the program to anticipate and recover from errors, thus making the
program more robust and resistant to unexpected conditions. By catching and handling exceptions,
the program can continue to execute and provide a more stable user experience.
3. Improves the Readability & Maintainability of the Code
Proper exception handling also improves the readability & maintainability of the code. By catching
and handling exceptions, the program can provide clear error messages that accurately describe the
error and provide information on how to resolve the issue. This makes it easier for developers to
understand and modify the code in the future. Additionally, by providing detailed error messages,
proper exception handling allows for more accurate error reporting, which is essential for debugging
and troubleshooting purposes.
4. Allows for more Accurate Error Reporting
Exception handling allows the program to catch & report errors in a more accurate & detailed
manner, providing valuable information to developers for debugging and troubleshooting purposes.
5. Facilitates Debugging and Troubleshooting
Exception handling allows the program to catch & report errors in a more accurate and detailed
manner, which facilitates debugging and troubleshooting. By providing detailed error messages and
stack traces, exception handling allows developers to quickly identify and resolve issues, reducing
the amount of time and resources required for debugging.
6. Improves the Security of the Program
Exception handling can also improve the security of a program by preventing sensitive information
from being exposed in the event of an error. By catching and handling exceptions, the program can
prevent sensitive information, such as passwords and personal data, from being displayed to the user
or logged-in error messages.
7. Provides a Better user Experience
Proper exception handling allows the program to anticipate and recover from errors, providing a
more stable user experience. It is particularly important for user-facing applications, as it ensures that
the program continues to function even in the event of an error, reducing the likelihood of user
frustration and abandonment.
8. Enables the use of error-recovery Mechanisms
Exception handling enables the use of error-recovery mechanisms, such as retries or fallbacks, which
can improve the reliability and availability of the program. For example, if a program encounters a
network error, it can retry the operation or fall back to a different network connection, ensuring that
the program continues to function even in the event of an error.
9. Improves the Scalability and Performance of the Program
Proper exception handling can also improve the scalability and performance of a program by
reducing the amount of unnecessary processing and resource consumption. By catching and handling
exceptions, the program can avoid performing unnecessary operations and releasing resources that
are no longer needed, reducing the overall load on the system and improving performance.

Acharya MCA
Acharya MCA

General form of Exception Handling


block try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed before try block ends
}
Different Approaches to handle Exceptions in Java:
We know that exceptions abnormally terminate the execution of a program. This is why it is important
to handle exceptions. Here's a list of different approaches to handle exceptions in Java.

Try Block

No

Exception Throws exception object

arise or
Catch Block
No Exceptional Handler
appropriate

Catch

block

Finally Block
Optional part

Acharya MCA
Acharya MCA

For Example:
class Exc0 {
public static void main(String
args[]) { int d = 0;
int a = 42 / d;
}
}

When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of
Exc0 to stop, because once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately.
Any exception that is not caught by your program will ultimately be processed by
the default handler. The default handler displays a string describing the exception,
prints a stack trace from the point at which the exception occurred, and terminates
the program. Here is the output generated when this example is executed.
java.lang.ArithmeticException
: / by zero at
Exc0.main(Exc0.java:4)

We know that exceptions abnormally terminate the execution of a program. This is why it
is important to handle exceptions. Here's a list of different approaches to handle exceptions
in Java.
 try...catch block
 finally block
 throw and throws keyword

1. Java try...catch block


The try-catch block is used to handle exceptions in Java. If an exception occurs within the
try block, the appropriate exception handler that is associated with the try block handles the
exception immediately following the try block, include a catch clause specifies the
exception type we wish to catch. A try block must have at least one catch block or finally
that allows it immediately. Here's the syntax of try...catch block:
try {
// code
}
catch(Exception e) {

Acharya MCA
Acharya MCA

// code
}
Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by a catch block.
Catch block
The catch block is used to process the exception raised. A try block can be one or more
catch blocks can handle a try block. Catch handles are placed immediately after the try
block. When an exception occurs, it is caught by the catch block. The catch block
cannot be used without the try block.

Example 1: Exception handling using try...catch


class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output:
ArithmeticException => / by zero

Example 2: Exception handling using try...catch


class MultipleCatch {

public static void main(String args[]) {


try {
int a = 15;
int b = 0;

System.out.println("Value of a = " + a);


System.out.println("Value of b = " + b);

Acharya MCA
Acharya MCA

int c = a / b;
System.out.println("a / b = " + c);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception has occurred in the program");
System.out.println("The message of the exception is: " + e.getMessage());
}
catch (Exception e) {
System.out.println("Some general Exeption has occurred in the program");
System.out.println("The message of the exception is: " + e.getMessage());
}
}
}

2. Java finally block


In Java, the finally block is always executed no matter whether there is an exception
or not.
The finally block is optional. And, for each try block, there can be only
one finally block.
The basic syntax of finally block is:
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
If an exception occurs, the finally block is executed after
the try...catch block. Otherwise, it is executed after the try block. For
each try block, there can be only one finally block.
Example: Java Exception Handling using finally block
class Main {
public static void main(String[] args) {
try {

Acharya MCA
Acharya MCA

// code that generates exception


int divideByZero = 5 / 0;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
Output:
ArithmeticException => / by zero
This is the finally block

Catch block
The catch block is used to process the exception raised. A try block can be
one or more catch blocks can handle a try block.
Catch handles are placed immediately after the try block.

Catch(exceptiontype e)
{
//Error handle routine is placed here for handling exception
}

Program 1

Class trycatch
{
Public static void main(String args[])
{
Int[] no={1,2,3};
Try
{
System.out.println(no[3]);

Acharya MCA
Acharya MCA

}
Catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Out of bonds”);
}
System.out.println(―Quit‖);
}
}

Output
Out of the Range Quit

Program 2:
class ArithExce
{
public static void main(String args[])
{
int a=10,b=0;
try
{
a=a/b;
System.out.println(―Won’t Print‖);
}
Catch(ArithmeticException e)
{
System.out.println(―Division by Zero error‖); System.out.println(―Change the b value‖);
}
System.out.println(―Quit‖);
}
}
Output
Division By zero error
change the B value
Quit

Acharya MCA
Acharya MCA

Note:
A try and its catch statement form a nit. We cannot use try block alone.
The compiler does not allow any statement between try block and its
associated catch block.

Acharya MCA
Acharya MCA

Multiple Catch Blocks

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.
The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
system.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no
command line parameters, since a will equal zero. It will survive the division if
you provide a command-line argument, setting a to something larger than
zero. But it will cause an

Acharya MCA
Acharya MCA

ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet


the program attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:\>java MultiCatch
a=0
Divide by 0:
java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch
TestArg a = 1
Array index oob:
java.lang.ArrayIndexOutOfBoundsException After
try/catch blocks.

Throw Keyword

So far, we have only been catching exceptions that are thrown by the Java
Run –Time systems. How ever, it is possible for our program to throw an
exception explicitly, using the throw statement.
Throw throwableInstance
Here, ThrowableInstance must be an object of type Throwable or a subclass
of Throwable. Simple types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions
There are two ways you can obtain a Throwable object:
– using a parameter into a catch clause
– creating one with the new operator.
The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed. The nearest enclosing try block is
inspected to see if it has a catch statement that matches the type of the
exception. If it does find a match, control is transferred to that statement. If
not, then the next enclosing try statement is inspected, and so on. If no
matching catch is found, then the default exception handler halts the
program and prints the stack trace

// Demonstrate throw.
class ThrowDemo {
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
Acharya MCA
Acharya MCA
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
}
catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

This program gets two chances to deal with the same error. First, main( )
sets up an exception context and then calls demoproc( ). The demoproc( )
method then sets up another exception-handling context and immediately
throws a new instance of NullPointerException, which is caught on the next
line. The exception is then rethrown. Here is the resulting output:

Caught inside demoproc.


Recaught: java.lang.NullPointerException: demo

The program also illustrates how to create one of J close attention to this line:

throw new NullPointerException("demo");

Here, new is used to construct an instance of NullPointerException. All of-


Java’ in run-time exceptions have at least two constructors: one with no
parameter and one that
takes a string parameter. When the second form is used, the argument
specifies a string that describes the exception.
This string is displayed when the object is used as an argument to print( )
or println( ).
It can also be obtained by a call to getMessage( ), which is defined by
Throwable.

Throws Keyword

If a method is capable of causing an exception that it does not handle, it


must specify this behavior so that callers of the method can guard themselves
against that exception.

You do this by including a throws clause in the method’s throws clause lists
declare the types of exceptions that a method might throw. This is necessary
Acharya MCA
Acharya MCA
for all exceptions, except those of type Error or RuntimeException, or any
of their subclasses. All other exceptions that a method can throw must be
declared in the throws clause. If they are not, a compile-time error will
result. This is the general form of a method declaration that includes a
throws clause:

type method-name(parameter-list) throws exception-list


{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw
Program
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{ System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e)
{
system.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException

S.No throw Throws


1 Java throw keyword is used to Java throws keyword is used to declare an
explicitly
2 Checked exception cannot be Checked exception can be propagated with using
propagated throw only
3 Throw is followed by an instance. Throws is followed by class.
4 Throw is used within the method. Throws is used with the method signature
5 You cannot throw multiple You can declare multiple exceptions e.g. public
exceptions. void method()throws IOException,SQLException

Acharya MCA
Acharya MCA

Finally block

 When exceptions are thrown, execution in a method takes a rather abrupt,


nonlinear path that alters the normal flow through the method. Depending upon
how the method is coded, it is even possible for an exception to cause the
method to return prematurely.
 This could be a problem in some methods. For example, if a method opens a file
upon entry and closes it upon exit, then you will not want the code that closes the
file to be bypassed by the exception-handling mechanism. The finally keyword is
designed to address this contingency.
 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.
 The finally block will execute whether or not an exception is thrown. If an
exception is thrown, the finally block will execute even if no catch statement
matches the exception.
 Any time a method is about to return to the caller from inside a try/catch block, via
an uncaught exception or an explicit return statement, the finally clause is also
executed just before the method returns. This can be useful for closing file handles
and freeing up any other resources that might have been allocated at the beginning
of a method with the intent of disposing of them before returning.
 The finally clause is optional. However, each try statement requires at least one
catch or a finally clause.

// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
system.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
system.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");

Acharya MCA
Acharya MCA
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
}
finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();
}
}
In this example, procA( ) prematurely breaks out of the try by throwing an
exception. The finally clause is executed on the way out. procB( )’stry
statement is exited via a return statement. The finally clause is executed
before procB( ) returns. In procC( ), the try statement executes normally,
without error. However, the finally block is still executed. If a finally block
is associated with a try, the finally block will be executed upon conclusion
of the try.

Here is the output generated by the preceding program:


inside procA
procA’s finally
Exception caught inside procB
procB’s finally
inside procC
procC’s finally

Acharya MCA
Acharya MCA

Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:

Acharya MCA
Acharya MCA

Java final example


class Example{
// declaring a final variable
final String name = "Soham";

void disp(){
// reassigining the name variable
// that throws compile time error
name = "Ganesh";
}

public static void main(String[] args) {


Example obj = new Example();
// executing disp method;
obj.disp();
}
}
Output:
Example.java:8: error: cannot assign a value to final variable name
name = "Ganesh";
^
1 error

Java finally example


class Example{
void disp(){
try{
System.out.println("Code inside try block");
// arithmetic exception
int val = 56/0;
System.out.println(val);
}
catch(Exception e){ // handling exception
System.out.println("Exception Handled Successfully");
// printing exception
System.out.println(e);
}
finally{
// the code inside finally block is always executed
System.out.println("This code is always executed");
}
// normally executing rest of the code
System.out.println("remaining code ...");
}
Acharya MCA
Acharya MCA
public static void main(String[] args) {
// creating object of the Example class
Example obj = new Example();
// executing disp method;
obj.disp();
}
}
Output:
Code inside try block
Exception Handled Successfully
java.lang.ArithmeticException: / by zero
This code is always executed
remaining code ...

Java finalize example


class Example {
public static void main(String[] args){

Example obj = new Example();


// printing the hashcode
System.out.println("Hashcode : " + obj.hashCode());
obj = null;

// gc() is used to call garbage collector


System.gc();
System.out.println("End of the garbage collection");
}
// defining the finalize method
protected void finalize(){
System.out.println("Called the finalize() method");
}
}
Output:
Hashcode : 498931366
End of the garbage collection
Called the finalize() method

Acharya MCA
Acharya MCA

Java Built –In Exceptions (Unchecked)


Inside the standard package java.lang, Java defines several exception classes. A
few have been used by the preceding examples. The most general of these
exceptions are subclasses of the standard type RuntimeException. Since
java.lang is implicitly imported into all Java programs, most exceptions derived
from RuntimeException are automatically available. Furthermore, they need not
be included throws list. In Java, these are called unchecked exceptions because the
compiler does not check to see if a method handles or throws these exceptions. The
unchecked exceptions defined in java.lang are listed in Table.

List of Unchecked exceptions

Acharya MCA
Acharya MCA

Examples:
1. ArithmeticException:
public class ArithmeticExceptionExample {

public static void main(String[] args) {


try {
int result = 30 / 0; // Trying to divide by zero
} catch (ArithmeticException e) {
System.err.println("ArithmeticException caught!");
e.printStackTrace();
}
}
}
Output:
ArithmeticException caught!
java.lang.ArithmeticException: / by zero
at com.javaguides.corejava.ArithmeticExceptionExample.main(ArithmeticExceptionExample

2. ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBounds {
public static void main(String[] args) {
int[] nums = new int[] {
1,
2,
3
};

try {
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
int numFromGreaterIndex = nums[4]; // Trying to access at greater index
int numFromLengthIndex = nums[3]; // Trying to access at index equal to size
of the array
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println("ArrayIndexOutOfBoundsException caught");
e.printStackTrace();
}
}
}
Output:
ArrayIndexOutOfBoundsException caught
java.lang.ArrayIndexOutOfBoundsException: -1
at com.javaguides.corejava.ArrayIndexOutOfBounds.main(ArrayIndexOutOfBounds.java:10)
Acharya MCA
Acharya MCA

3. ClassCastException
The ClassCastException is a runtime exception that Java throws when code
attempts to cast an object to a subclass it doesn't belong to. In simpler terms, it arises
when we mistakenly try to treat one type of object as another incompatible type.
Here is a very simple example, an Integer object cannot be cast to a String object:
Example:
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = new Integer(100);
System.out.println((String) obj);
}
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be
cast to java.lang.String
at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)

User Defined Exceptions (Checked exceptions)


We can create our own exception by extending exception class.
The throw and throws keywords are used while implementing user defined exceptions

1.ClassNotFoundException:
The ClassNotFoundException is a checked exception that signals the Java Runtime
Environment (JRE) cannot find the specified class in its classpath during runtime. It's
important to note that this is different from the NoClassDefFoundError, which occurs
when the class was available during compile-time but not at runtime.

The below example demonstrates the common causes


of java.lang.ClassNotFoundException is using Class.forName or ClassLoader.loadClass
Acharya MCA
Acharya MCA
to load a class by passing the string name of a class and it’s not found on the classpath.

public class ClassNotFoundExceptionExample {


public static void main(String[] args) {
try {
Class.forName("com.javaguides.corejava.Demo");
ClassLoader.getSystemClassLoader().loadClass("com.javaguides.corejava.Demo");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
java.lang.ClassNotFoundException: com.javaguides.corejava.Demo
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.javaguides.corejava.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:9)

2. FileNotFoundException:
FileNotFoundException is a checked exception in Java, which means you're required to
handle it, either by catching it or declaring it in the method signature using the throws
keyword. It's thrown primarily by the Java I/O system when attempting to access a file
that doesn't exist or isn't accessible for some reason.
In the below example, an invalid path location passed to the File constructor leads
to this exception.
import java.io.BufferedReader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileNotFoundExceptionExample {

public static void main(String[] args) {

BufferedReader reader = null;


try {
reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
} catch (FileNotFoundException e) {

Acharya MCA
Acharya MCA
System.err.println("FileNotFoundException caught!");
e.printStackTrace();
}
}
}
Output:
FileNotFoundException caught!
java.io.FileNotFoundException: \invalid\file\location (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at com.javaguides.corejava.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:15)

3. InterruptedException:
When a thread is blocked (waiting, sleeping, or occupied with some long-running
operations) and another thread interrupts it by invoking its interrupt() method, the
blocked thread throws an InterruptedException. This mechanism allows threads to be
stopped, queried, and controlled.

In the below example, note that the thread interrupted in the main() method throws
an InterruptedException exception that is handled in the run() method.

class ChildThread extends Thread {


public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("InterruptedException caught!");
e.printStackTrace();
}
}
}

public class InterruptedExceptionExample {


public static void main(String[] args) throws InterruptedException {
ChildThread childThread = new ChildThread();
childThread.start();
childThread.interrupt();
}
}
Output:
InterruptedException caught!
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
Acharya MCA
Acharya MCA
at com.javaguides.corejava.ChildThread.run(InterruptedExceptionExample.java:7)

Acharya MCA
Acharya MCA

Creating own Exception sub classes:


The Java programming language allow us to create our own exception classes
which are basically subclasses built-in class Exception.
To create our own exception class simply create a class as a subclass of built-in Exception
class.
We may create constructor in the user-defined exception class and pass a string to
Exception class constructor using super(). We can use getMessage() method to access the
string.
Let's look at the following Java code that illustrates the creation of user-defined exception.
import java.util.Scanner;
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg);
}
}

class VoterList{
int age;
VoterList(int age){
this.age = age;
}

void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {

Scanner input = new Scanner(System.in);


System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList person = new VoterList(age);
person.checkEligibility();
}
}
Acharya MCA
Acharya MCA
Output:
Enter your age in years:
16
Error: Not eligible for vote due to under age.

Example 2:
// This program creates a custom exception type.

class MyException extends Exception {


private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) { try {
compute(1);
compute(20);
}
catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]

Acharya MCA

You might also like