SlideShare ist ein Scribd-Unternehmen logo
1 von 22
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling
Exception handling Exception handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
exception handling
exception handlingexception handling
exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 

Andere mochten auch

Andere mochten auch (20)

12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Javaexceptions
JavaexceptionsJavaexceptions
Javaexceptions
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception handling java
Exception handling javaException handling java
Exception handling java
 
Exception
ExceptionException
Exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Um presentation (1)
Um presentation (1)Um presentation (1)
Um presentation (1)
 
Java: Exception Handling
Java: Exception HandlingJava: Exception Handling
Java: Exception Handling
 
Exception Handling in Scala
Exception Handling in ScalaException Handling in Scala
Exception Handling in Scala
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and Logging
 

Ähnlich wie Exception handling

Ähnlich wie Exception handling (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Exeption handling
Exeption handlingExeption handling
Exeption handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Chap12
Chap12Chap12
Chap12
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdf
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 

Mehr von Shashwat Shriparv (20)

Learning Linux Series Administrator Commands.pptx
Learning Linux Series Administrator Commands.pptxLearning Linux Series Administrator Commands.pptx
Learning Linux Series Administrator Commands.pptx
 
LibreOffice 7.3.pptx
LibreOffice 7.3.pptxLibreOffice 7.3.pptx
LibreOffice 7.3.pptx
 
Kerberos Architecture.pptx
Kerberos Architecture.pptxKerberos Architecture.pptx
Kerberos Architecture.pptx
 
Suspending a Process in Linux.pptx
Suspending a Process in Linux.pptxSuspending a Process in Linux.pptx
Suspending a Process in Linux.pptx
 
Kerberos Architecture.pptx
Kerberos Architecture.pptxKerberos Architecture.pptx
Kerberos Architecture.pptx
 
Command Seperators.pptx
Command Seperators.pptxCommand Seperators.pptx
Command Seperators.pptx
 
Upgrading hadoop
Upgrading hadoopUpgrading hadoop
Upgrading hadoop
 
Hadoop migration and upgradation
Hadoop migration and upgradationHadoop migration and upgradation
Hadoop migration and upgradation
 
R language introduction
R language introductionR language introduction
R language introduction
 
Hive query optimization infinity
Hive query optimization infinityHive query optimization infinity
Hive query optimization infinity
 
H base introduction & development
H base introduction & developmentH base introduction & development
H base introduction & development
 
Hbase interact with shell
Hbase interact with shellHbase interact with shell
Hbase interact with shell
 
H base development
H base developmentH base development
H base development
 
Hbase
HbaseHbase
Hbase
 
H base
H baseH base
H base
 
My sql
My sqlMy sql
My sql
 
Apache tomcat
Apache tomcatApache tomcat
Apache tomcat
 
Linux 4 you
Linux 4 youLinux 4 you
Linux 4 you
 
Introduction to apache hadoop
Introduction to apache hadoopIntroduction to apache hadoop
Introduction to apache hadoop
 
Next generation technology
Next generation technologyNext generation technology
Next generation technology
 

Kürzlich hochgeladen

WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Hiroshi SHIBATA
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfFIDO Alliance
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 

Kürzlich hochgeladen (20)

WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 

Exception handling