1
Exception Handling in Java
Shashwat Shriparv
dwivedishashwat@gmail.com
InfinitySoft
2
Exception Handling in Java
throw
It is possible to throw an exception explicitly.
Syntax:
throw ThrowableInstance
throwableInstance must be an object of type Throwable or a
subclass of Throwable.
By 2 ways v can obtain a Throwable object
1.Using parameter into a catch clause
2.Creating one with new operator
3
class throwDemo
{
public static void main(String s[])
{
int size;
int arry[]=new int[3];
size=Integer.parseInt(s[0]);
try
{
if(size<=0)
throw new NegativeArraySizeException("Illegal Array size");
for(int i=0;i<3;i++)
arry[i]+=i+1;
}
catch(NegativeArraySizeException e)
{
System.out.println(e);
throw e; //rethrow the exception
}
}
}
new operator used
parameter used into catch clause
4
throws
If a method causing an exception that it doesn't
handle, it must specify this behavior that callers of the
method can protect themselves against the exception.
This can be done by using throws clause.
throws clause lists the types of exception that a
method might throw.
Form
type methodname(parameter list) throws Exception list
{//body of method}
5
import java.io.*;
class ThrowsDemo
{
psvm(String d[])throws IOException,NumberFormatException
{
int i;
InputStreamReader is=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
i=Integer.parseInt(br.readLine());
System.output.println(i);
}}
6
finally
It creates a block of code that will b executed after try/catch block has
completed and before the code following try/catch block.
It will execute whether or not an exception is thrown
finally is useful for:
•Closing a file
•Closing a result set
•Closing the connection established with db
This block is optional but when included is placed after the last catch
block of a try
7
Form:
try
{}
catch(exceptiontype e)
{}
finally
{} finally
finally
Catch block
try block
8
Java Exception Type Hierarchy
10
Object
Throwable
Error Exception
LinkageError
ThreadDeath
VirtualMachineError
AWTError
RunTimeException
ArithmeticException
IndexOutOfBoundsException
IllegalArguementException
IllegalAccessException
NoSuchMethodException
ClassNotFoundException
NumberFormatException
StringIndexOutOfBoundsException
11
12
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IndexOutOfBoundsException
IllegalStateException
NullPointerException
SecurityException
The types of exceptions that need not be included in a
method’s throws list are called Unchecked Exceptions.
Unchecked Exceptions
13
ArithmeticException
ArrayIndexOutOfBoundsException
ArrayStoreException
ClassCastException
IllegalArgumentException
IllegalMonitorStateException
IllegalStateException
IllegalThreadStateException
IndexOutOfBoundsException
NegativeArraySizeException
Exception
Arithmetic error, such as divide-by-zero.
Array index is out-of-bounds.
Assignment to an array element of an incompatible type.
Invalid cast.
Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on an unlocked
thread.
Environment or application is in incorrect state.
Requested operation not compatible with current thread state.
Some type of index is out-of-bounds.
Array created with a negative size.
Meaning
Unchecked Exceptions
14
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
The types of exceptions that must be included in a method’s
throws list if that method can generate one of these
exceptions and does not handle it ,are called Checked
Exceptions.
Checked Exceptions
15
Checked Exceptions
Class not found.
Attempt to clone an object that does not implement the
Cloneable interface.
Access to a class is denied.
Attempt to create an object of an abstract class or interface.
One thread has been interrupted by another thread.
A requested field does not exist.
A requested method does not exist.
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
Exception Meaning
• A checked exception is any subclass of Exception (or
Exception itself), excluding class RuntimeException
and its subclasses.
• Making an exception checked forces client
programmers to deal with the possibility that the
exception will be thrown.
• eg, IOException thrown by java.io.FileInputStream's
read() method .
• Unchecked exceptions are RuntimeException and any
of its subclasses. Class Error and its subclasses also
are unchecked.
16
Java’s Built-in Exceptions: inside java.lang package
• With an unchecked exception, however, the compiler
doesn't force client programmers either to catch the
exception or declare it in a throws clause.
• In fact, client programmers may not even know that
the exception could be thrown.
• eg, StringIndexOutOfBoundsException thrown by
String's charAt() method.
• Checked exceptions must be caught at compile time.
Runtime exceptions do not need to be.
17
18
Creating our own Exception class
For creating an exception class our own simply make
our class as subclass of the super class Exception.
Eg:
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
19
class TestMyException
{
public static void main(String d[])
{
int x=5,y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01)
{
throw new MyException("too small number");
}
}
20
catch(MyException me)
{
System.out.println("caught my exception");
System.out.println(me.getMessage());
}
finally
{
System.out.println("from finally");
}
}
}
• E:JAVAPGMS>java TestMyException
• caught my exception
• too small number
• from finally
Output
21
Making safer program by
providing special mechanism
Objective of Exception Handling
Summary
22
Thank you
Shashwat Shriparv
dwivedishashwat@gmail.com
InfinitySoft

More Related Content

PPTX
Exceptions in java
PDF
Built in exceptions
PPT
Java exception
PPT
exception handling in java
PPTX
Exception handling in Java
PPT
PPT
Exception handling
PPTX
Exception handling
Exceptions in java
Built in exceptions
Java exception
exception handling in java
Exception handling in Java
Exception handling
Exception handling

What's hot (20)

ODP
Exception handling in java
PPTX
Exception handling in Java
PPTX
Exception handling in java
PPTX
Java exception handling
PPT
Types of exceptions
PDF
Java - Exception Handling Concepts
PPTX
Exception Handling in Java
PPT
Exception Handling in JAVA
PPTX
Java exception handling
PPT
Exception handling
PPTX
Exception handling in java
PPT
exception handling
PPTX
Exception Handling in Java
PPTX
Exceptional Handling in Java
PPTX
Java - Exception Handling
PPTX
Exception handling in java
PPT
Java: Exception
PPT
Multi catch statement
PPTX
L14 exception handling
Exception handling in java
Exception handling in Java
Exception handling in java
Java exception handling
Types of exceptions
Java - Exception Handling Concepts
Exception Handling in Java
Exception Handling in JAVA
Java exception handling
Exception handling
Exception handling in java
exception handling
Exception Handling in Java
Exceptional Handling in Java
Java - Exception Handling
Exception handling in java
Java: Exception
Multi catch statement
L14 exception handling
Ad

Viewers also liked (20)

PPT
12 exception handling
PPTX
Exception handling in java
PPT
12 exception handling
PDF
Javaexceptions
PPTX
17 exceptions
PPTX
Exception handling java
PPTX
Exception
PDF
Java exception handling
PPT
Um presentation (1)
PDF
Java: Exception Handling
DOCX
Exception Handling in Scala
PPT
Unit 5 Java
PPT
6. Exception Handling
PDF
javaexceptions
PDF
Java Day-5
PDF
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
PDF
Exception handling
DOCX
Java Exception handling
PPTX
Exception handling in java
PPTX
Java Exception Handling, Assertions and Logging
12 exception handling
Exception handling in java
12 exception handling
Javaexceptions
17 exceptions
Exception handling java
Exception
Java exception handling
Um presentation (1)
Java: Exception Handling
Exception Handling in Scala
Unit 5 Java
6. Exception Handling
javaexceptions
Java Day-5
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Exception handling
Java Exception handling
Exception handling in java
Java Exception Handling, Assertions and Logging
Ad

Similar to Exception handling (20)

PPSX
Java Exceptions
PPSX
Java Exceptions Handling
PPTX
Exception handling in java
PPTX
Java -Exception handlingunit-iv
PDF
Java unit 11
PPTX
Java exception handling
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
PPTX
Exception handling in java.pptx
PDF
16 exception handling - i
PPTX
Interface andexceptions
PPTX
Lec-01 Exception Handling in Java_javatpoint.pptx
PPTX
Event handling
PPT
Exception and ErrorHandling in Java .ppt
PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
exception handling in java
PPTX
using Java Exception Handling in Java.pptx
PPTX
EXCEPTION HANDLING in prograaming
PPTX
Exceptionhandling
PPT
Exception handling
PPTX
Java-Unit 3- Chap2 exception handling
Java Exceptions
Java Exceptions Handling
Exception handling in java
Java -Exception handlingunit-iv
Java unit 11
Java exception handling
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
Exception handling in java.pptx
16 exception handling - i
Interface andexceptions
Lec-01 Exception Handling in Java_javatpoint.pptx
Event handling
Exception and ErrorHandling in Java .ppt
Ch-1_5.pdf this is java tutorials for all
exception handling in java
using Java Exception Handling in Java.pptx
EXCEPTION HANDLING in prograaming
Exceptionhandling
Exception handling
Java-Unit 3- Chap2 exception handling

More from Shashwat Shriparv (20)

PPTX
Learning Linux Series Administrator Commands.pptx
PPTX
LibreOffice 7.3.pptx
PPTX
Kerberos Architecture.pptx
PPTX
Suspending a Process in Linux.pptx
PPTX
Kerberos Architecture.pptx
PPTX
Command Seperators.pptx
DOCX
Upgrading hadoop
PPTX
Hadoop migration and upgradation
PPTX
R language introduction
PPTX
Hive query optimization infinity
PPTX
H base introduction & development
PPTX
Hbase interact with shell
PPT
H base development
PPTX
PPTX
PPTX
Apache tomcat
PPTX
Linux 4 you
PDF
Introduction to apache hadoop
DOCX
Next generation technology
Learning Linux Series Administrator Commands.pptx
LibreOffice 7.3.pptx
Kerberos Architecture.pptx
Suspending a Process in Linux.pptx
Kerberos Architecture.pptx
Command Seperators.pptx
Upgrading hadoop
Hadoop migration and upgradation
R language introduction
Hive query optimization infinity
H base introduction & development
Hbase interact with shell
H base development
Apache tomcat
Linux 4 you
Introduction to apache hadoop
Next generation technology

Recently uploaded (20)

PDF
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
PDF
Decision Optimization - From Theory to Practice
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
PDF
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
PPTX
Information-Technology-in-Human-Society (2).pptx
PDF
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Addressing the challenges of harmonizing law and artificial intelligence tech...
PDF
Advancements in abstractive text summarization: a deep learning approach
PDF
substrate PowerPoint Presentation basic one
PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
PPTX
CRM(Customer Relationship Managmnet) Presentation
PDF
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
PDF
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
PDF
Child-friendly e-learning for artificial intelligence education in Indonesia:...
PPTX
How to use fields_get method in Odoo 18
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PDF
Peak of Data & AI Encore: Scalable Design & Infrastructure
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
Decision Optimization - From Theory to Practice
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
Information-Technology-in-Human-Society (2).pptx
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
NewMind AI Journal Monthly Chronicles - August 2025
Presentation - Principles of Instructional Design.pptx
Addressing the challenges of harmonizing law and artificial intelligence tech...
Advancements in abstractive text summarization: a deep learning approach
substrate PowerPoint Presentation basic one
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
CRM(Customer Relationship Managmnet) Presentation
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
Child-friendly e-learning for artificial intelligence education in Indonesia:...
How to use fields_get method in Odoo 18
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
Peak of Data & AI Encore: Scalable Design & Infrastructure

Exception handling