Java Exception Handling
Java Exception Handling
class Main{
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
printStackTrace()
This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.
toString()
The toString() method prints exception information in the format of the
Name of the exception: description of the exception.
getMessage()
The getMessage() method prints only the description of the exception.
class Main{
public static void main(String[] args) {
try
{
Integer in = new Integer(“abc");
in=12/0;
System.out.println(in);
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic " + e);
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception " + e);
}
}
}
Ms Anosha Khan 02/24/2024 13
Example for Unreachable Catch block
public class Main
{
public static void main(String[] args)
{
try While using multiple catch block, always make sure that sub-
{
int a[]=new int[10];
classes of Exception class comes before any of their super
System.out.println(a[20]); classes. Else you will get compile time error.
}
catch(Exception e)
{
System.out.println("Arithmetic Exception --> "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception --> "+e);
}
catch(Exception e)
{
System.out.println(e);
Ms Anosha Khan
} 02/24/2024 14
}
}
Nested try statement
class Main
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x = arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
throws is a keyword in Java that is used in the signature of a method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.
Syntax of Java throws
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the exceptions which a method might throw.
In a program, if there is a chance of raising an exception then the compiler always warns us
about it and compulsorily we should handle that checked exception, Otherwise, we will get
compile time error saying unreported exception XXX must be caught or declared to be
thrown. To prevent this compile time error we can handle the exception in two ways:
By using try catch
By using the throws keyword
We can use the throws keyword to delegate the responsibility of exception handling to the
caller (It may be a method or JVM) then the caller method is responsible to handle that
exception.
}
Types of Builtin Exceptions in Java
ArithmeticException: It is thrown when an exceptional condition has
occurred in an arithmetic operation.
ArrayIndexOutOfBoundsException: 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.
ClassNotFoundException: This Exception is raised when we try to access
a class whose definition is not found
FileNotFoundException: This Exception is raised when a file is not
accessible or does not open.
IOException: It is thrown when an input-output operation failed or
interrupted
InterruptedException: It is thrown when a thread is waiting, sleeping,
or doing some processing, and it is interrupted.
Ms Anosha Khan 02/24/2024 23
NoSuchFieldException: It is thrown when a class does not contain the field (or variable)
specified
NoSuchMethodException: It is thrown when accessing a method that is not found.
NullPointerException: This exception is raised when referring to the members of a null
object. Null represents nothing
NumberFormatException: This exception is raised when a method could not convert a
string into a numeric format.
RuntimeException: This represents an exception that occurs during runtime.
StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an
index is either negative or greater than the size of the string
IllegalArgumentException : This exception will throw the error or error statement when
the method receives an argument which is not accurately fit to the given relation or
condition. It comes under the unchecked exception.
IllegalStateException : This exception will throw an error or error message when the
method is not accessed for the particular operation in the application. It comes under the
unchecked exception.
For example
https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/
Ms Anosha Khan 02/24/2024 24
User-defined Custom Exception in Java
Java provides us the facility to create our own exceptions which are basically
derived classes of Exception. Creating our own Exception is known as a custom
exception or user-defined exception. Basically, Java custom exceptions are used
to customize the exception according to user needs. In simple words, we can say
that a User-Defined Exception or custom exception is creating your own
exception class and throwing that exception using the ‘throw’ keyword.
Why use custom exceptions?
Java exceptions cover almost all the general types of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
Following are a few of the reasons to use custom exceptions:
To catch and provide specific treatment to a subset of existing Java exceptions.
Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the
exact problem
}
Another way class MyException extends Exception {
String msg;
MyException(String msg){
this.msg=msg;
System.out.println("my fun");
}
public String getMessage(){
return msg;
}}
public class Main {
public static void main(String args[]){
try {
throw new MyException("my msg");
}
catch (MyException ex) {
System.out.println("Caught");
Ms Anosha Khan
System.out.println(ex.getMessage());
02/24/2024 27
} } }
Java try with Resource Statement
try with resource is a new feature of Java that was introduced in Java 7 and further improved in Java
9. This feature add another way to exception handling with resources management. It is also referred
as automatic resource management. It close resources automatically by using AutoCloseable
interface..
Resource can be any like: file, connection etc and we don't need to explicitly close these, JVM will do
this automatically.
Suppose, we run a JDBC program to connect to the database then we have to create a connection and
close it at the end of task as well. But in case of try-with-resource we don’t need to close the
connection, JVM will do this automatically by using AutoCloseable interface.
Try with Resource Syntax
try(resource-specification(there can be more than one resource))
This try statement contains a parenthesis in which one or
{ more resources is declared. Any object that implements
//use the resource java.lang.AutoCloseable or java.io.Closeable, can be
passed as a parameter to try statement. A resource is an
}
object that is used in program and must be closed after
catch() the program is finished. The try-with-resources
{ statement ensures that each resource is closed at the
// handler code end of the statement of the try block. We do not have to
Ms Anosha Khan
explicitly close the resources. 02/24/2024 28
}
Example without using try with Resource Statement
class Main{
public static void main(String[] args){
try {
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br = new BufferedReader(new FileReader("d:\\
myfile.txt"));
while((str=br.readLine())!=null){
System.out.println(str);
}
br.close(); //closing BufferedReader stream
}
catch(IOException ie){
System.out.println("I/O Exception "+ie);
}
Example try with Resource Statement
import java.io.*;
class Car{
public static void main(String[] args){
try(BufferedReader br = new BufferedReader(new
FileReader("myfile.txt"))){
String str;
while((str = br.readLine()) != null){
System.out.println(str);
}
}
catch(IOException ie){
System.out.println("I/O Exception "+ie);
}
}
Ms Anosha Khan 02/24/2024 30
}
Points to Remember