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

Chapter 4.1

Uploaded by

Apurv Musandi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 4.1

Uploaded by

Apurv Musandi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Unit: IV

Exception Handling in Java

Mr. Prashant B. Patil


SY CSE-A,B JPR
2024-2025
4.1 Exception Handling in Java
 The Exception Handling in Java is one of the
powerful mechanism to handle the runtime errors so that normal
flow of the application can be maintained.

 An exception (or exceptional event) is a problem that arises


during the execution of a program.

 When an Exception occurs the normal flow of the program is


disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be
handled.
4.1 Exception Handling in Java
An exception can occur for many different reasons. Following are
some scenarios where an exception occurs.

 A user has entered an invalid data.

 A file that needs to be opened cannot be found.

 A network connection has been lost in the middle of


communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by


programmer error, and others by physical resources that have
failed in some manner.
4.1 Exception Handling in Java
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 use exception handling.

statement 1; Suppose there are 10 statements in your


statement 2; program and there occurs an exception at
statement 3; statement 5, the rest of the code will not
statement 4; be executed i.e. statement 6 to 10 will not
statement 5;//
be executed.
exception occurs statement 6;
statement 7;
If we perform exception handling, the rest
statement 8; of the statement will be executed.
statement 9; That is why we use exception handling
statement 10; in Java.
4.1 Exception Handling in Java – Error & Types of Errors
Error is a situation which prevents the normal execution of our
program.

 It is obvious responsibility of a programmer to deal with all kinds


of errors.

 Types of Errors : Compile Time Error (Syntax Error)

Run-Time Error

Logic Error
4.1 Exception Handling in Java –Types of Errors

1. Compile Time Error (Syntax Error):

 Errors that occur during compiling the program and if there any
syntax error in the program like missing semicolon at the end of a
statement or curly braces etc., then the Java compiler displays
the error on to the screen.
class demo
{
public static void main(String[] args)
{
int i=10;

//Missing semicolon at the end of the statement

System.out.println(i)
}
}
4.1 Exception Handling in Java –Types of Errors

1. Compile Time Error (Syntax Error):

Common Examples are:

 Misplaced variable and function names.


 Missing semicolons.
 Improperly matching parentheses, square brackets and curly
braces.
 Incorrect format in semicolon and loop statements etc.
4.1 Exception Handling in Java –Types of Errors
2. Run Time Error:
 Run Time errors are occurs during execution of program.
 Java compiler will not detect Run Time errors. Only Java Virtual
Machine (JVM) will detect it while executing the program.

class demo
{
public static void main(String[] args)
{
int a[]=new int[4];
a[5]=10;
System.out.println("Success");
}
}
4.1 Exception Handling in Java –Types of Errors
3. Logic Error:
 In Java logical error is nothing but when a program is compiled
and executed without any error but not producing any result is
called as logical error. These errors can’t be detected by neither
compiler nor JVM.

class demo
{
public static void main(String[] args)
{
int a=100;
int b=10;
int c= a*b;
System.out.println("a divide by b =>"+c);
}
}
4.1 Exception Handling in Java –Types of Exceptions

 Exceptions are the unwanted errors or bugs or events that


restrict the normal execution of a program.

Each time an exception occurs, program execution gets disrupted.


An error message is displayed on the screen.

 There are several reasons behind the occurrence of exceptions.

These are some conditions where an exception occurs:

• Whenever a user provides invalid data.


• The file requested to be accessed does not exist in the system.
• When the Java Virtual Machine (JVM) runs out of memory.
•Network drops in the middle of communication.
4.1 Exception Handling in Java –Types of Exceptions

Not Checked at
Compile Time

Checked at Compile
Time
4.1 Exception Handling in Java –Types of Exceptions

1. Built in Exception:
 Exceptions that are already available in Java libraries are referred
to as built-in exception.

 These exceptions are able to define the error situation so that we


can understand the reason of getting this error.
4.1 Exception Handling in Java –Types of Exceptions

1. Built in Exception:
 The unchecked exceptions are
Checked exceptions are just opposite to
called compile-time exceptions the checked exceptions. The
because these exceptions are compiler will not check these
checked at compile-time by the exceptions at compile time.
compiler. The compiler ensures
whether the programmer  In simple words, if a program
handles the exception or not. throws an unchecked exception,
and even if we didn't handle or
The programmer should have declare it, the program would not
to handle the exception; give a compilation error. Usually, it
otherwise, the system has shown occurs when the user provides bad
a compilation error. data during the interaction with
the program.
4.1 Exception Handling in Java –Types of Exceptions

2. User Defined Exception

In Java, we can write our own exception class by extends


the Exception class.

 We can throw our own exception on a particular


condition using the throw keyword.

 For creating a user-defined exception, we should have


basic knowledge of the try-catch block
and throw keyword.
4.1 try & catch Statement

 The try statement allows


you to define a block of code try
to be tested for errors while {
it is being executed. // Block of code to try

 The catch statement }


allows you to define a block catch(Exception e)
of code to be executed, if an {
error occurs in the try block. // Block of code to handle
errors
The try and catch keywords
come in pairs.
}
4.1 try & catch Statement

try
{
-------
-------
}
catch(------)
{
-------
-------
}
4.1 try & catch Statement
Consider following example:
4.1 try & catch Statement
4.1 try & catch Statement
class demo
{
public static void main(String[] args)
{
try
{
int a = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " +
e.getMessage());
}
}
}
Output:

ArithmeticException => / by zero


4.1 Nested try Statement

 The try block within a try block is known as nested try


block in java.

Why use nested try block:

 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.


4.1 Nested try Statement

....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)

{
}
}
catch(Exception e)
{
}
class demo
{
public static void main(String args[])
{ catch(Exception e)
try {
{ System.out.println(“Index 5 out of bounds
try for length 5");
{ }
System.out.println("going to divide"); System.out.println("normal flow..");
int b =39/0; }
} }
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=14;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
4.1 Multiple catch Blocks

A try block can be followed by one or more catch


blocks. Each catch block must contain a different
exception handler.

 So, if you have to perform different tasks at the


occurrence of different exceptions, use java multi-catch
block.
4.1 Multiple catch Blocks

try catch(------)
{ {
------- -------
------- -------
} }
catch(------) catch(-----)
{ {
------- -------
------- -------
} }
4.1 Multiple catch Blocks
public class demo
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
}
}
4.1 finally statement

 Java finally block is a block that is used to execute


important code such as closing connection, stream etc.

 Java finally block is always executed whether


exception is handled or not.

 Java finally block follows try or catch block.


4.1 finally statement
4.1 finally statement

try catch(------)
{ {
------- -------
------- -------
} }
catch(------) finally
{ {
------- -------
------- -------
} }
class Division
{
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try Finally Statement -
{
result = a / (b - c); Example
System.out.println("result" + result);
}
catch (ArithmeticException e)
{
System.out.println(“Divide by 0 is not possible.");
}
finally
{
System.out.println("I am in final block");
}
}
}
4.1 throw Statement
 The Java throw keyword is used to explicitly throw an
exception.
 We can throw either checked or uncheked exception in java by
throw keyword.
 The throw keyword is mainly used to throw custom exception.

Syntax:
throw new exception(“Some message”);
Example:
throw new ArithmeticException(“Error Message”);
throw new NumberFormatException(“Error
Message”);
throw new IOException(“Error Message”);
4.1 throw Statement - Example
public class MyClass
{
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args)
{
checkAge(15); // Set age to 15 (which is below 18...)
}
}
4.1 throws Statement
 The throws keyword indicates what exception type may be
thrown by a method.

Syntax:
return_type method_name() throws exception
{
//method code
}
Or
return_type method_name() throws exception1,exception2
{
//method code
}
4.1 throws Statement - Example
public class demo
{
static void divide() throws ArithmeticException
{
int x=5, y=0, z;
z=x/y;
}
public static void main(String[] args)
{
try
{
divide();
}
catch(ArithmeticException e)
{
System.out.println(“Caught the exception” +e);
}
}
}
Built-in Exceptions in Java
 Java defines several exception classes inside the standard
package java.lang.
Sr.No. Exception & Description Unchecked
ArithmeticException Exceptions
1
Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException
2
Array index is out-of-bounds.
ArrayStoreException
3
Assignment to an array element of an incompatible type.
ClassCastException
4
Invalid cast.
IllegalArgumentException
5
Illegal argument used to invoke a method.
IllegalMonitorStateException
6
Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException
7
Environment or application is in incorrect state.
Sr.No. Exception & Description
IllegalThreadStateException
8
Requested operation not compatible with the current thread state.
IndexOutOfBoundsException
9
Some type of index is out-of-bounds.
NegativeArraySizeException
10
Array created with a negative size.
NullPointerException
11
Invalid use of a null reference.
NumberFormatException
12
Invalid conversion of a string to a numeric format.
SecurityException
13
Attempt to violate security.
StringIndexOutOfBounds
14
Attempt to index outside the bounds of a string.
UnsupportedOperationException
15
An unsupported operation was encountered.
Sr.No. Exception & Description
ClassNotFoundException
1
Class not found.
CloneNotSupportedException
2 Attempt to clone an object that does not implement the Cloneable
interface.
IllegalAccessException
3
Access to a class is denied.
InstantiationException
4
Attempt to create an object of an abstract class or interface.
InterruptedException
5
One thread has been interrupted by another thread.
NoSuchFieldException
6
A requested field does not exist.
NoSuchMethodException
7
A requested method does not exist.
Checked
Exceptions
4.1 Chained Exception in Java
 This feature allow you to relate one exception with another
exception, i.e one exception describes cause of another
exception.
 For example, consider a situation in which a method throws
an ArithmeticException because of an attempt to divide by
zero but the actual cause of exception was an I/O error which
caused the divisor to be zero.
 The method will throw only ArithmeticException to the
caller.
 So the caller would not come to know about the actual cause
of exception.
 Chained Exception is used in such type of situations.
4.1 Chained Exception in Java

 getCause() and initCause() are the two methods added to


Throwable class.

1. getCause() : method returns the actual cause associated with


current exception.

2. initCause() : set an underlying cause(exception) with invoking


exception.
import java.io.IOException;
public class ChainedException
{
public static void main(String args[])
{ try
{
ArithmeticException ae = new ArithmeticException(“Exception");
ae.initCause(new IOException(“This is actual cause…"));
//Setting a cause of exception
throw ae;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
System.out.println(ae.getCause());//getting actual cause of exception
}
}
OUTPUT:

java.lang.ArithmeticException : Exception
java.io.IOException : This is actual cause….
2.1 User-defined Custom Exception in Java
 Java provides us facility to create our own exceptions
which are basically derived classes of Exception.
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");

}
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

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


}

You might also like