0% found this document useful (0 votes)
5 views

Java Module-4

Exception Handling in Java is a mechanism to manage runtime errors, ensuring the application's normal flow is maintained. It involves using keywords like try, catch, and finally to handle exceptions, which can be categorized into checked and unchecked exceptions. The document also provides examples of exception handling scenarios, illustrating how to use try-catch blocks effectively to prevent program termination due to errors.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Module-4

Exception Handling in Java is a mechanism to manage runtime errors, ensuring the application's normal flow is maintained. It involves using keywords like try, catch, and finally to handle exceptions, which can be categorized into checked and unchecked exceptions. The document also provides examples of exception handling scenarios, illustrating how to use try-catch blocks effectively to prevent program termination due to errors.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Exception Handling:

The Exception Handling in Java is one of the powerful mechanism to handle


the runtime errors so that the normal flow of the application can be maintained.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of
the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10
will not be executed. However, when we perform exception handling, the rest of
the statements will be executed. That is why we use exception handling in Java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.

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.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by
a try-catch block.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They
are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.
Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must
be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.

Java try block must be followed by either catch or finally block.


Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple
catch block with a single try block.
Internal Working of Java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception
occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

Problem without exception handling


Let's try to understand the problem if we don't use a try-catch block.
Example 1
TryCatchExample1.java
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
Example 2
TryCatchExample2.java
public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e.,
the rest of the code statement is printed.
Example 3
In this example, we also kept the code in a try block that will not throw an
exception.
TryCatchExample3.java
public class TryCatchExample3 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not ex
ceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}

}
}
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 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

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 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}

}
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 {

public static void main(String[] args) {


int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Example 7
In this example, along with try block, we also enclose exception code in a catch
block.
TryCatchExample7.java
public class TryCatchExample7 {

public static void main(String[] args) {

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

public class TryCatchExample8 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception

}
// 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 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

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;

public class TryCatchExample10 {

public static void main(String[] args) {

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:

File saved successfully


Throw:
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be
related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception

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.

Example 1: Throwing Unchecked Exception


In this example, we have created a method named validate() that accepts an
integer as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Output:

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.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked exception
in Java. A checked exception is everything else under the Throwable class.

TestThrow2.java
import java.io.*;

public class TestThrow2 {

//function to check if person is eligible to vote or not


public static void method() throws FileNotFoundException {

FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.


txt");
BufferedReader fileInput = new BufferedReader(file);

throw new FileNotFoundException();

}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.
TestThrow3.java
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-
defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
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:

Difference between throw and throws in Java

Sr. Basis of Throw throws


no. Differences

1. Definition Java throw keyword is Java throws keyword is used in


used throw an exception the method signature to declare
explicitly in the code, an exception which might be
inside the function or the thrown by the function while
block of code. the execution of the code.

2. Usage Type of exception Using Using throws keyword, we can


throw keyword, we can declare both checked and
only propagate unchecked unchecked exceptions.
exception i.e., the checked However, the throws keyword
exception cannot be can be used to propagate
propagated using throw checked exceptions only.
only.

3. Syntax The throw keyword is The throws keyword is


followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.

4. Declaration throw is used within the throws is used with the method
method. signature.

5. Internal We are allowed to throw We can declare multiple


implementation only one exception at a exceptions using throws
time i.e. we cannot throw keyword that can be thrown by
multiple exceptions. the method. For example,
main() throws IOException,
SQLException.
Finally
Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.
The finally block follows the try-catch block.
Flowchart of finally block

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");
}

System.out.println("rest of phe code...");


}
}

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 {

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

Output:

Case 3: When an exception occurs and is handled by the catch block


Example:
Let's see the following example where the Java code throws an exception and
the catch block handles the exception. Later the finally block is executed after
the try-catch block. Further, the rest of the code is also executed normally.
TestFinallyBlock2.java
public class TestFinallyBlock2{
public static void main(String args[]){

try {
System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}
Output:

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

3. ClassNotFoundException : This Exception is raised when we try to access a


class whose definition is not found.
// Java program to illustrate the concept of ClassNotFoundException
class College {

}
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

4. FileNotFoundException : This Exception is raised when a file is not


accessible or does not open.
// Java program to demonstrate FileNotFoundException

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

5. IOException : It is thrown when an input-output operation failed or


interrupted
// Java program to illustrate IOException
import java.io.*;

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

7. NoSuchMethodException : t is thrown when accessing a method which is


not found.
// Java Program to illustrate NoSuchMethodException
class NSME {
public NSME() {
try {
Class<?> i = Class.forName("java.lang.String");
try {
i.getMethod("someMethod", Class[].class);
} catch (SecurityException | NoSuchMethodException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


new NSME();
}
}
}
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
8. NullPointerException : This exception is raised when referring to the
members of a null object. Null represents nothing
// 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..");
}
}
}

Output:
NullPointerException..

9. NumberFormatException : This exception is raised when a method could


not convert a string into a numeric format.
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo {
public static void main(String[] args) {
try {
// "navkis" is not a number
int num = Integer.parseInt("navkis");
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}

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.

// Java program to demonstrate StringIndexOutOfBoundsException

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

Creating own exception sub classes


Java provides rich set of built-in exception classes like: ArithmeticException,
IOException, NullPointerException etc. all are available in the java.lang
package and used in exception handling. These exceptions are already set to
trigger on pre-defined conditions such as when you divide a number by zero it
triggers ArithmeticException.
Apart from these classes, Java allows us to create our own exception class to
provide own exception implementation. These type of exceptions are called
user-defined exceptions or custom exceptions.
You can create your own exception simply by extending java Exception class.
You can define a constructor for your Exception (not compulsory) and you can
override the toString() function to display your customized message on catch.
Lets see an example.
Example: Custom Exception
In this example, we are creating an exception class MyException that extends
the Java Exception class and
class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex = a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

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);
}
}

public static void main(String[] args)


{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined
Exception
}
}
}
Output:
MyException[-10] is less than zero

Example: Custom Exception


Here we created a class ItemNotFound that extends the Exception class and
helps to generate our own exception implementation.

class ItemNotFound extends Exception


{
public ItemNotFound(String s) {
super(s);
}
}

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");
}
}

public static void main(String[] args)


{
try
{
find(new int[]{12,25,45}, 10);
}
catch(ItemNotFound i)
{
System.out.println(i);
}
}
}

Output:
ItemNotFound: Item Not Found

You might also like