尊敬的 微信汇率:1円 ≈ 0.046166 元 支付宝汇率:1円 ≈ 0.046257元 [退出登录]
SlideShare a Scribd company logo
Exception Handling
By :-
SURIT DATTA
Contents
 What is an Exception ?
 Error vs. Exception
 Hierarchy of Java Exception classes
 Java Exception Handling Keywords
 Types of Exception in Java
 Internal working of java try-catch block
 Exception Handler
 Java Multi Catch block
 The Throws / Throw Keywords
 The finally block
 Common scenarios where exceptions may occur
 Sequence of Events for throw
 Checked Exceptions
 Un-Checked Exceptions
 User-defined Exceptions:
What is an exception?
 Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
 What is exception handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound,
IO, SQL, Remote etc.
 Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application
that is why we use exception handling.
Error vs Exception
 Errors: An error represents a
condition serious enough that
most reasonable applications
should not try to catch.
 Virtual Machine Error
 Out of memory
 Stack overflow
 Thread Death
 Linkage Error
 Exceptions: An error
which reasonable
applications should
catch.
 Array index out of bounds
 Arithmetic errors (divide by
zero
 Null Pointer Exception
 I/O Exceptions
Hierarchy of Java Exception classes
Object
Throwable
Exception Error
IOException
SQLException
Runtime Exception
ArithmeticException
NullPointerException
VirtualMachineError
AssertionError
Java Exception Handling Keywords
 There are 5 keywords used in java exception handling.
 Try : Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
Java try block must be followed by either catch or finally block.
 Catch : Java catch block is used to handle the Exception. It must be used after the try block only.
We can use multiple catch block with a single try.
 Finally : Executes whether or not an exception is thrown in the corresponding try block or any of its
corresponding catch blocks.
Throw : You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
Throws : If a method does not handle a checked exception, the method must declare it using
the throws keyword.
Types of Exception in Java
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
NegativeArraySizeException
NullPointerException
NumberFormatException
NoSuchMethodException
Internal working of java try-catch block
int data = 10/0; Exception 
object
An object of exception class is thrown
Is  Handled ?
YES
NOJVM
1.Prints out exception 
description
2.Prints the stack trace
3.Terminates the program
Rest of code 
is executed
Exception Handler
Exception
"thrown" here
Exception
handler
Exception
handler
Thrown exception matched against
first set of exception handlers
Thrown exception matched against
first set of exception handlers
If it fails to match, it is matched against
next set of handlers, etc.
If it fails to match, it is matched against
next set of handlers, etc.
If exception matches none of handlers,
program is abandoned
If exception matches none of handlers,
program is abandoned
public class TestMultipleCatchBlock{  
  public static void main(String args[]){  
   try{  
    int a[]=new int[5];  
    a[5]=30/0;  
   }  
   catch(ArithmeticException e){System.out.println("task1 is completed");}  
   catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}  
   catch(Exception e){System.out.println("common task completed");}  
  
   System.out.println("rest of the code...");  
 }  
}  
At a time only one Exception is occurred and at a time only one catch
block is executed.
All catch blocks must be ordered from most specific to most general i.e.
catch for ArithmeticException must come before catch for Exception .
Java Multi Catch block
The Throws / Throw Keywords
 If a method does not handle a checked exception, the method must
declare it using the throws keyword. The throws keyword appears at
the end of a method's signature.
 You can throw an exception, either a newly instantiated one or an
exception that you just caught, by using the throw keyword.
 ***throws is used to postpone the handling of a checked exception 
and throw is used to invoke an exception explicitly.***
import java.io.*;
public class className
{ public void deposit(double amount) throws RemoteException
{ // Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
The finally block
 The finally block follows a try block or a catch block. A finally block of code
always executes, irrespective of occurrence of an Exception.
 Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.
 A finally block appears at the end of the catch blocks and has the following
syntax:
try
{ //Protected code
}catch(ExceptionType1 e1)
{ //Catch block }
catch(ExceptionType2 e2)
{ //Catch block }
finally { //The finally block always executes. }
Common scenarios where exceptions may occur
 ArithmeticException occurs
int a=50/0; //ArithmeticException
 NullPointerException occurs
String s=null;
System.out.println(s.length()); //NullPointerException
 NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
 ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Sequence of Events for throw
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Checked Exceptions
Inherit from class Exception but not from
RuntimeException
Compiler enforces catch-or-declare requirement
Compiler checks each method call and method
declaration
Checked exceptions are checked at compile-time.
e.g. IOException, SQLException etc.
Unchecked Exceptions
Inherit from class RuntimeException or class Error
Compiler does not check code to see if exception caught
or declared
If an unchecked exception occurs and not caught
- Program terminates or runs with unexpected results
Can typically be prevented by proper coding
User-defined Exceptions:
 We can create your own exceptions in Java. Keep the following
points in mind when writing your own exception classes.
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically
enforced by the Handle or Declare Rule, you need to extend the
Exception class.
 If you want to write a runtime exception, you need to extend the
RuntimeException class.
 We can define our own Exception class as below:
class MyException extends Exception{ }
Exception Handling in JAVA

More Related Content

What's hot

Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
sharqiyem
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Java I/O
Java I/OJava I/O
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Java Collections
Java  Collections Java  Collections
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
OOP java
OOP javaOOP java
OOP java
xball977
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
Niloy Saha
 

What's hot (20)

Java string handling
Java string handlingJava string handling
Java string handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Packages in java
Packages in javaPackages in java
Packages in java
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception
Java exception Java exception
Java exception
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
OOP java
OOP javaOOP java
OOP java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 

Viewers also liked

Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
Arriz San Juan
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
priyankazope
 
Exception
ExceptionException
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
Miquel Martin
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 

Viewers also liked (9)

Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
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
ExceptionException
Exception
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 

Similar to Exception Handling in JAVA

Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Kavitha713564
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
TharuniDiddekunta
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
exception handling
exception handlingexception handling
exception handling
Manav Dharman
 

Similar to Exception Handling in JAVA (20)

Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
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 PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
exception handling
exception handlingexception handling
exception handling
 

Recently uploaded

Kandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book Now
Kandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book NowKandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book Now
Kandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book Now
SONALI Batra $A12
 
Call Girls Madurai 8824825030 Escort In Madurai service 24X7
Call Girls Madurai 8824825030 Escort In Madurai service 24X7Call Girls Madurai 8824825030 Escort In Madurai service 24X7
Call Girls Madurai 8824825030 Escort In Madurai service 24X7
Poonam Singh
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
Pallavi Sharma
 
一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理
一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理
一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理
nonods
 
Better Builder Magazine, Issue 49 / Spring 2024
Better Builder Magazine, Issue 49 / Spring 2024Better Builder Magazine, Issue 49 / Spring 2024
Better Builder Magazine, Issue 49 / Spring 2024
Better Builder Magazine
 
Data Communication and Computer Networks Management System Project Report.pdf
Data Communication and Computer Networks Management System Project Report.pdfData Communication and Computer Networks Management System Project Report.pdf
Data Communication and Computer Networks Management System Project Report.pdf
Kamal Acharya
 
🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...
🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...
🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...
sonamrawat5631
 
Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)
Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)
Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)
Tsuyoshi Horigome
 
Lateral load-resisting systems in buildings.pptx
Lateral load-resisting systems in buildings.pptxLateral load-resisting systems in buildings.pptx
Lateral load-resisting systems in buildings.pptx
DebendraDevKhanal1
 
Cricket management system ptoject report.pdf
Cricket management system ptoject report.pdfCricket management system ptoject report.pdf
Cricket management system ptoject report.pdf
Kamal Acharya
 
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfSri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Balvir Singh
 
My Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdfMy Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdf
Geoffrey Wardle. MSc. MSc. Snr.MAIAA
 
Online train ticket booking system project.pdf
Online train ticket booking system project.pdfOnline train ticket booking system project.pdf
Online train ticket booking system project.pdf
Kamal Acharya
 
Technological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdfTechnological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdf
tanujaharish2
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
drshikhapandey2022
 
一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
gapboxn
 
❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...
❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...
❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...
hotchicksescort
 
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC ConduitThe Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
Guangdong Ctube Industry Co., Ltd.
 
Literature review for prompt engineering of ChatGPT.pptx
Literature review for prompt engineering of ChatGPT.pptxLiterature review for prompt engineering of ChatGPT.pptx
Literature review for prompt engineering of ChatGPT.pptx
LokerXu2
 
FUNDAMENTALS OF MECHANICAL ENGINEERING.pdf
FUNDAMENTALS OF MECHANICAL ENGINEERING.pdfFUNDAMENTALS OF MECHANICAL ENGINEERING.pdf
FUNDAMENTALS OF MECHANICAL ENGINEERING.pdf
EMERSON EDUARDO RODRIGUES
 

Recently uploaded (20)

Kandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book Now
Kandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book NowKandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book Now
Kandivali Call Girls ☑ +91-9967584737 ☑ Available Hot Girls Aunty Book Now
 
Call Girls Madurai 8824825030 Escort In Madurai service 24X7
Call Girls Madurai 8824825030 Escort In Madurai service 24X7Call Girls Madurai 8824825030 Escort In Madurai service 24X7
Call Girls Madurai 8824825030 Escort In Madurai service 24X7
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
 
一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理
一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理
一比一原版(psu学位证书)美国匹兹堡州立大学毕业证如何办理
 
Better Builder Magazine, Issue 49 / Spring 2024
Better Builder Magazine, Issue 49 / Spring 2024Better Builder Magazine, Issue 49 / Spring 2024
Better Builder Magazine, Issue 49 / Spring 2024
 
Data Communication and Computer Networks Management System Project Report.pdf
Data Communication and Computer Networks Management System Project Report.pdfData Communication and Computer Networks Management System Project Report.pdf
Data Communication and Computer Networks Management System Project Report.pdf
 
🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...
🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...
🔥Young College Call Girls Chandigarh 💯Call Us 🔝 7737669865 🔝💃Independent Chan...
 
Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)
Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)
Update 40 models( Solar Cell ) in SPICE PARK(JUL2024)
 
Lateral load-resisting systems in buildings.pptx
Lateral load-resisting systems in buildings.pptxLateral load-resisting systems in buildings.pptx
Lateral load-resisting systems in buildings.pptx
 
Cricket management system ptoject report.pdf
Cricket management system ptoject report.pdfCricket management system ptoject report.pdf
Cricket management system ptoject report.pdf
 
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfSri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
 
My Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdfMy Airframe Metallic Design Capability Studies..pdf
My Airframe Metallic Design Capability Studies..pdf
 
Online train ticket booking system project.pdf
Online train ticket booking system project.pdfOnline train ticket booking system project.pdf
Online train ticket booking system project.pdf
 
Technological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdfTechnological Innovation Management And Entrepreneurship-1.pdf
Technological Innovation Management And Entrepreneurship-1.pdf
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
 
一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
 
❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...
❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...
❣Unsatisfied Bhabhi Call Girls Surat 💯Call Us 🔝 7014168258 🔝💃Independent Sura...
 
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC ConduitThe Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
The Differences between Schedule 40 PVC Conduit Pipe and Schedule 80 PVC Conduit
 
Literature review for prompt engineering of ChatGPT.pptx
Literature review for prompt engineering of ChatGPT.pptxLiterature review for prompt engineering of ChatGPT.pptx
Literature review for prompt engineering of ChatGPT.pptx
 
FUNDAMENTALS OF MECHANICAL ENGINEERING.pdf
FUNDAMENTALS OF MECHANICAL ENGINEERING.pdfFUNDAMENTALS OF MECHANICAL ENGINEERING.pdf
FUNDAMENTALS OF MECHANICAL ENGINEERING.pdf
 

Exception Handling in JAVA

  • 2. Contents  What is an Exception ?  Error vs. Exception  Hierarchy of Java Exception classes  Java Exception Handling Keywords  Types of Exception in Java  Internal working of java try-catch block  Exception Handler  Java Multi Catch block  The Throws / Throw Keywords  The finally block  Common scenarios where exceptions may occur  Sequence of Events for throw  Checked Exceptions  Un-Checked Exceptions  User-defined Exceptions:
  • 3. What is an exception?  Exception is an abnormal condition. In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.  What is exception handling Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.  Advantage of Exception Handling The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling.
  • 4. Error vs Exception  Errors: An error represents a condition serious enough that most reasonable applications should not try to catch.  Virtual Machine Error  Out of memory  Stack overflow  Thread Death  Linkage Error  Exceptions: An error which reasonable applications should catch.  Array index out of bounds  Arithmetic errors (divide by zero  Null Pointer Exception  I/O Exceptions
  • 5. Hierarchy of Java Exception classes Object Throwable Exception Error IOException SQLException Runtime Exception ArithmeticException NullPointerException VirtualMachineError AssertionError
  • 6. Java Exception Handling Keywords  There are 5 keywords used in java exception handling.  Try : Java try block is used to enclose the code that might throw an exception. It must be used within the method. Java try block must be followed by either catch or finally block.  Catch : Java catch block is used to handle the Exception. It must be used after the try block only. We can use multiple catch block with a single try.  Finally : Executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks. Throw : You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Throws : If a method does not handle a checked exception, the method must declare it using the throws keyword.
  • 7. Types of Exception in Java ArithmeticException ArrayIndexOutOfBoundsException ClassCastException IllegalArgumentException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException NoSuchMethodException
  • 8. Internal working of java try-catch block int data = 10/0; Exception  object An object of exception class is thrown Is  Handled ? YES NOJVM 1.Prints out exception  description 2.Prints the stack trace 3.Terminates the program Rest of code  is executed
  • 9. Exception Handler Exception "thrown" here Exception handler Exception handler Thrown exception matched against first set of exception handlers Thrown exception matched against first set of exception handlers If it fails to match, it is matched against next set of handlers, etc. If it fails to match, it is matched against next set of handlers, etc. If exception matches none of handlers, program is abandoned If exception matches none of handlers, program is abandoned
  • 11. The Throws / Throw Keywords  If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.  You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.  ***throws is used to postpone the handling of a checked exception  and throw is used to invoke an exception explicitly.*** import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
  • 12. The finally block  The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.  Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.  A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } finally { //The finally block always executes. }
  • 13. Common scenarios where exceptions may occur  ArithmeticException occurs int a=50/0; //ArithmeticException  NullPointerException occurs String s=null; System.out.println(s.length()); //NullPointerException  NumberFormatException occurs String s="abc"; int i=Integer.parseInt(s); //NumberFormatException  ArrayIndexOutOfBoundsException occurs int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
  • 14. Sequence of Events for throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step
  • 15. Checked Exceptions Inherit from class Exception but not from RuntimeException Compiler enforces catch-or-declare requirement Compiler checks each method call and method declaration Checked exceptions are checked at compile-time. e.g. IOException, SQLException etc.
  • 16. Unchecked Exceptions Inherit from class RuntimeException or class Error Compiler does not check code to see if exception caught or declared If an unchecked exception occurs and not caught - Program terminates or runs with unexpected results Can typically be prevented by proper coding
  • 17. User-defined Exceptions:  We can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes.  All exceptions must be a child of Throwable.  If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.  If you want to write a runtime exception, you need to extend the RuntimeException class.  We can define our own Exception class as below: class MyException extends Exception{ }
  翻译: