Chapter 4.1
Chapter 4.1
Mr. R. M. Patil
Subject : JPR
2023-24
SY CO
1
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.
2
4.1 Exception Handling in Java
An exception can occur for many different reasons. Following are
some scenarios where an exception occurs.
3
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.
Run-Time Error
Logic Error
5
4.1 Exception Handling in Java –Types of Errors
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;
System.out.println(i)
}
} 6
4.1 Exception Handling in Java –Types of Errors
7
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");
}
}
8
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);
}
}
9
4.1 Exception Handling in Java –Types of Exceptions
Not Checked at
Compile Time
Checked at Compile
Time
11
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.
12
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.
13
4.1 Exception Handling in Java –Types of Exceptions
14
Homework
1. State and explain different types of errors in
Java. W14, S18, 4M
15
4.1 try & catch Statement Exception Handling
Keywords
try
17
4.1 try & catch Statement
try
{
-------
-------
}
catch(------)
{
-------
-------
}
18
4.1 try & catch Statement
Consider following example:
19
4.1 try & catch Statement
20
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:
22
4.1 Nested try Statement
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
----------------
}
}
catch(Exception e)
{
---------------
} 23
class demo
{
public static void main(String args[])
{ catch(Exception e)
try {
{ System.out.println("handeled");
try }
{ System.out.println("normal flow..");
System.out.println("going to divide"); }
int b =39/0; }
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
} 24
}
4.1 Multiple catch Blocks
25
4.1 Multiple catch Blocks
try catch(------)
{ {
------- -------
------- -------
} }
catch(------) catch(-----)
{ {
------- -------
------- -------
} }
26
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");
}
}
} 27
4.1 finally statement
28
4.1 finally statement
29
4.1 finally statement
try catch(------)
try { {
{ ------- -------
------- ------- -------
------- } }
} catch(------) finally
finally { {
{ ------- -------
------- ------- -------
------- } }
}
30
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");
}
}
}
31
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 NemberFormatException(“Error Message”);
throw new IOException(“Error Message”);
32
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...)
}
}
33
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
}
34
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);
}
}
} 35
Difference between Throw & Throws
Homework
1. How exception is handled?
S15,W15,W16 – 4M
Or
Explain the following clause w.r.t. exception handling:
(i)try (ii) catch
W15,W17,S18 – 4M
39
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
40
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.
41
4.1 Chained Exception in Java
42
import java.io.IOException;
super(s);
}
}
45
// A Class that uses above MyException
public class Main
{
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException(“Example-Own Exception");
}
System.out.println(ex.getMessage());
} Output:
}
} Exception Caught
Example-Own Exception
46