SlideShare a Scribd company logo
EXCEPTION HANDLING IN JAVA
Explained By:
Aniket & Mayank
Department of Computer Application
OBJECTIVES
• Introduction
• What exceptions are for
• Catching & Throwing exceptions
• Exception Specifications
• Standard Java Exceptions
• Exceptions and Polymorphism
• The finally clause
• Resource Management
• Uncaught Exceptions
EXCEPTION
• In Java, an exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. These exceptions can occur for various
reasons, such as
• Invalid User Input,
• File not found, or
• Division by zero.
EXCEPTION HANDLING
Exception Handling is a mechanism to handle runtime errors such as
• ClassNotFoundException,
• IOException,
• SQLException,
• RemoteException, etc.
EXCEPTION HIERARCHY
TYPES OF EXCEPTION
In Java, exceptions are categorized into two main types: checked exceptions and
unchecked exceptions. Additionally, there is a third category known as errors. Let’s
delve into each of these types:
Checked Exception/Compile Time Exception
Unchecked Exception/Runtime Exception
• Error
Checked exceptions are the exceptions that are checked at compile-time.This means that the compiler
verifies that the code handles these exceptions either by catching them or declaring them in the method
signature using the throws keyword. Examples of checked exceptions include:
IOException: An exception is thrown when an input/output operation fails, such as when reading from or
writing to a file.
SQLException: It is thrown when an error occurs while accessing a database.
ParseException: Indicates a problem while parsing a string into another data type, such as parsing a date.
• ClassNotFoundException: It is thrown when an application tries to load a class through its string name
using methods like Class.forName(), but the class with the specified name cannot be found in the
classpath.
CHECKED EXCEPTION
• Unchecked exceptions, also known as runtime exceptions, are not checked at compile-time. These
exceptions usually occur due to programming errors, such as logic errors or incorrect assumptions in the
code. They do not need to be declared in the method signature using the throws keyword, making it
optional to handle them. Examples of unchecked exceptions include:
• NullPointerException: It is thrown when trying to access or call a method on an object reference that is
null.
• ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an invalid
index.
• ArithmeticException: It is thrown when an arithmetic operation fails, such as division by zero.
• IllegalArgumentException: It indicates that a method has been passed an illegal or inappropriate
argument.
UNCHECKED EXCEPTION
• Errors represent exceptional conditions that are not expected to be caught under normal
circumstances.They are typically caused by issues outside the control of the application, such as
system failures or resource exhaustion. Errors are not meant to be caught or handled by
application code. Examples of errors include:
• OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate enough
memory for the application.
• StackOverflowError: It is thrown when the stack memory is exhausted due to excessive
recursion.
• NoClassDefFoundError: It indicates that the JVM cannot find the definition of a class that was
available at compile-time.
ERROR
EXCEPTION KEYWORDS
Keywords Description
try
The “try” keyword is used to specify a block where we should place an exception code. It
means we can’t use try block alone. The try block must be followed by either catch or finally.
catch
The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally
The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws
The “throws” keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn’t throw an exception. It is always used with method
signature.
EXCEPTION HANDLING EXAMPLE
THE TRY-CATCH BLOCK
• One of the primary mechanisms for handling exceptions in Java is the try-catch
block. The try block contains the code that may throw an exception, and the catch
block is used to handle the exception if it occurs. Here’s a basic example:
ERRORS AND ERROR HANDLING
• Some typical causes of errors:
• Memory errors (i.e. memory incorrectly allocated, memory leaks,“null pointer”)
• File system errors (i.e. disk is full, disk has been removed)
• Network errors (i.e. network is down, URL does not exist)
• Calculation errors (i.e. divide by 0)
ERRORS AND ERROR HANDLING
• More typical causes of errors:
• Array errors (i.e. accessing element –1)
• Conversion errors (i.e. convert ‘q’ to a number)
• Can you think of some others?
ERRORS AND ERROR HANDLING
• Exceptions – a better error handling
• Exceptions are a mechanism that provides the best of both worlds.
• Exceptions act similar to method return flags in that any method may raise and exception
should it encounter an error.
• Exceptions act like global error methods in that the exception mechanism is built into
Java; exceptions are handled at many levels in a program, locally and/or globally.
EXCEPTIONS
• How do you handle exceptions?
• To handle the exception, you write a “try-catch” block. To pass the exception “up the
chain”, you declare a throws clause in your method or class declaration.
• If the method contains code that may cause a checked exception, you MUST handle the
exception OR pass the exception to the parent class (remember, every class has Object as
the ultimate parent)
CODING EXCEPTIONS
• Coding Exceptions
• Try-Catch Mechanism
• Wherever your code may trigger an exception, the normal code logic is placed inside a
block of code starting with the “try” keyword:
• After the try block, the code to handle the exception should it arise is placed in a block of
code starting with the “catch” keyword.
STANDARD JAVA EXCEPTIONS
Throwable
Exceptio
n
Error
Runtime
Exception
IO
Exception
CATCHING EXCEPTIONS
• Wrap code to be checked in a try-block
• checking occurs all the way down the execution stack
• try-blocks can be nested
• control resumes at most enclosed matching handler
CODING EXCEPTIONS
• Example
• try {
… normal program code
}
catch(Exception e) {
… exception handling code
}
CODING EXCEPTIONS
• Types of Exceptions
• Examples:
• public void myMethod throws Exception {
• public void myMethod throws IOException {
• try { … }
catch (Exception e) { … }
• try { … }
catch (IOException ioe) { … }
CODE EXAMPLES
• 1. Demonstration of an unchecked exception (NullPointerException)
• 2. Demonstration of checked exceptions:
• Passing a DivideByZeroException
• Handling a DivideByZeroException
EXAMPLE
class error2
{
public static void main(String arg[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
Y=a/(b-c);
System.out.println(“y=“+y);
}
}
In the previous program we cannot see the value of x just because of the error in the
value of y, that is division by zero but when we use the try and catch blocks in
exception handling then we can see the value of y which is correct and our program
will display an error message shown in the try block.
CONCLUSION
• Exceptions are a powerful error handling mechanism.
• Exceptions in Java are built into the language.
• Exceptions can be handled by the programmer (try-catch), or handled by the Java
environment (throws).
• Exception handling can only hide the errors.
• It cannot correct the errors.
Ad

More Related Content

Similar to JAVA Exception Handling in java programing (20)

how to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppthow to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppt
soneedison007
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
JAYESHRODGE
 
Exception Handling ppt slide presentation
Exception Handling ppt slide presentationException Handling ppt slide presentation
Exception Handling ppt slide presentation
madduriradha
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Lec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptxLec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptx
MdNazmulHasanRuhan1
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
Varshini62
 
exception-handling-in-java programming.ppt
exception-handling-in-java programming.pptexception-handling-in-java programming.ppt
exception-handling-in-java programming.ppt
ansariparveen06
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
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
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
Java2Blog
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
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 Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
how to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppthow to do exception-handling-in-java.ppt
how to do exception-handling-in-java.ppt
soneedison007
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
JAYESHRODGE
 
Exception Handling ppt slide presentation
Exception Handling ppt slide presentationException Handling ppt slide presentation
Exception Handling ppt slide presentation
madduriradha
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Lec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptxLec-01 Exception Handling in Java_javatpoint.pptx
Lec-01 Exception Handling in Java_javatpoint.pptx
MdNazmulHasanRuhan1
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
Varshini62
 
exception-handling-in-java programming.ppt
exception-handling-in-java programming.pptexception-handling-in-java programming.ppt
exception-handling-in-java programming.ppt
ansariparveen06
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
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
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
Java2Blog
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
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 Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 

Recently uploaded (20)

A report on the county distress rankings in NC
A report on the county distress rankings in NCA report on the county distress rankings in NC
A report on the county distress rankings in NC
Mebane Rash
 
PUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for HealthPUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for Health
JonathanHallett4
 
Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............
19lburrell
 
20250515 Ntegra San Francisco 20250515 v15.pptx
20250515 Ntegra San Francisco 20250515 v15.pptx20250515 Ntegra San Francisco 20250515 v15.pptx
20250515 Ntegra San Francisco 20250515 v15.pptx
home
 
How to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale OrderHow to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale Order
Celine George
 
Capitol Doctoral Presentation -May 2025.pptx
Capitol Doctoral Presentation -May 2025.pptxCapitol Doctoral Presentation -May 2025.pptx
Capitol Doctoral Presentation -May 2025.pptx
CapitolTechU
 
How to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 InventoryHow to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 Inventory
Celine George
 
Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
businessweekghana
 
The Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional DesignThe Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional Design
Sean Michael Morris
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf
paulinelee52
 
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdfIPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
Quiz Club of PSG College of Arts & Science
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
The History of Kashmir Lohar Dynasty NEP.ppt
The History of Kashmir Lohar Dynasty NEP.pptThe History of Kashmir Lohar Dynasty NEP.ppt
The History of Kashmir Lohar Dynasty NEP.ppt
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 WebsiteHow to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 Website
Celine George
 
A report on the county distress rankings in NC
A report on the county distress rankings in NCA report on the county distress rankings in NC
A report on the county distress rankings in NC
Mebane Rash
 
PUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for HealthPUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for Health
JonathanHallett4
 
Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............
19lburrell
 
20250515 Ntegra San Francisco 20250515 v15.pptx
20250515 Ntegra San Francisco 20250515 v15.pptx20250515 Ntegra San Francisco 20250515 v15.pptx
20250515 Ntegra San Francisco 20250515 v15.pptx
home
 
How to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale OrderHow to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale Order
Celine George
 
Capitol Doctoral Presentation -May 2025.pptx
Capitol Doctoral Presentation -May 2025.pptxCapitol Doctoral Presentation -May 2025.pptx
Capitol Doctoral Presentation -May 2025.pptx
CapitolTechU
 
How to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 InventoryHow to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 Inventory
Celine George
 
Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
businessweekghana
 
The Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional DesignThe Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional Design
Sean Michael Morris
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf
paulinelee52
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 WebsiteHow to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 Website
Celine George
 
Ad

JAVA Exception Handling in java programing

  • 1. EXCEPTION HANDLING IN JAVA Explained By: Aniket & Mayank Department of Computer Application
  • 2. OBJECTIVES • Introduction • What exceptions are for • Catching & Throwing exceptions • Exception Specifications • Standard Java Exceptions • Exceptions and Polymorphism • The finally clause • Resource Management • Uncaught Exceptions
  • 3. EXCEPTION • In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. These exceptions can occur for various reasons, such as • Invalid User Input, • File not found, or • Division by zero.
  • 4. EXCEPTION HANDLING Exception Handling is a mechanism to handle runtime errors such as • ClassNotFoundException, • IOException, • SQLException, • RemoteException, etc.
  • 6. TYPES OF EXCEPTION In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions. Additionally, there is a third category known as errors. Let’s delve into each of these types: Checked Exception/Compile Time Exception Unchecked Exception/Runtime Exception • Error
  • 7. Checked exceptions are the exceptions that are checked at compile-time.This means that the compiler verifies that the code handles these exceptions either by catching them or declaring them in the method signature using the throws keyword. Examples of checked exceptions include: IOException: An exception is thrown when an input/output operation fails, such as when reading from or writing to a file. SQLException: It is thrown when an error occurs while accessing a database. ParseException: Indicates a problem while parsing a string into another data type, such as parsing a date. • ClassNotFoundException: It is thrown when an application tries to load a class through its string name using methods like Class.forName(), but the class with the specified name cannot be found in the classpath. CHECKED EXCEPTION
  • 8. • Unchecked exceptions, also known as runtime exceptions, are not checked at compile-time. These exceptions usually occur due to programming errors, such as logic errors or incorrect assumptions in the code. They do not need to be declared in the method signature using the throws keyword, making it optional to handle them. Examples of unchecked exceptions include: • NullPointerException: It is thrown when trying to access or call a method on an object reference that is null. • ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an invalid index. • ArithmeticException: It is thrown when an arithmetic operation fails, such as division by zero. • IllegalArgumentException: It indicates that a method has been passed an illegal or inappropriate argument. UNCHECKED EXCEPTION
  • 9. • Errors represent exceptional conditions that are not expected to be caught under normal circumstances.They are typically caused by issues outside the control of the application, such as system failures or resource exhaustion. Errors are not meant to be caught or handled by application code. Examples of errors include: • OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate enough memory for the application. • StackOverflowError: It is thrown when the stack memory is exhausted due to excessive recursion. • NoClassDefFoundError: It indicates that the JVM cannot find the definition of a class that was available at compile-time. ERROR
  • 10. EXCEPTION KEYWORDS Keywords Description try The “try” keyword is used to specify a block where we should place an exception code. It means we can’t use try block alone. The try block must be followed by either catch or finally. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The “throws” keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn’t throw an exception. It is always used with method signature.
  • 12. THE TRY-CATCH BLOCK • One of the primary mechanisms for handling exceptions in Java is the try-catch block. The try block contains the code that may throw an exception, and the catch block is used to handle the exception if it occurs. Here’s a basic example:
  • 13. ERRORS AND ERROR HANDLING • Some typical causes of errors: • Memory errors (i.e. memory incorrectly allocated, memory leaks,“null pointer”) • File system errors (i.e. disk is full, disk has been removed) • Network errors (i.e. network is down, URL does not exist) • Calculation errors (i.e. divide by 0)
  • 14. ERRORS AND ERROR HANDLING • More typical causes of errors: • Array errors (i.e. accessing element –1) • Conversion errors (i.e. convert ‘q’ to a number) • Can you think of some others?
  • 15. ERRORS AND ERROR HANDLING • Exceptions – a better error handling • Exceptions are a mechanism that provides the best of both worlds. • Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error. • Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.
  • 16. EXCEPTIONS • How do you handle exceptions? • To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a throws clause in your method or class declaration. • If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class (remember, every class has Object as the ultimate parent)
  • 17. CODING EXCEPTIONS • Coding Exceptions • Try-Catch Mechanism • Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: • After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword.
  • 19. CATCHING EXCEPTIONS • Wrap code to be checked in a try-block • checking occurs all the way down the execution stack • try-blocks can be nested • control resumes at most enclosed matching handler
  • 20. CODING EXCEPTIONS • Example • try { … normal program code } catch(Exception e) { … exception handling code }
  • 21. CODING EXCEPTIONS • Types of Exceptions • Examples: • public void myMethod throws Exception { • public void myMethod throws IOException { • try { … } catch (Exception e) { … } • try { … } catch (IOException ioe) { … }
  • 22. CODE EXAMPLES • 1. Demonstration of an unchecked exception (NullPointerException) • 2. Demonstration of checked exceptions: • Passing a DivideByZeroException • Handling a DivideByZeroException
  • 23. EXAMPLE class error2 { public static void main(String arg[]) { int a=10; int b=5; int c=5; int x,y; try { x=a/(b-c); } catch(ArithmeticException e) { System.out.println(“Division by Zero”); } Y=a/(b-c); System.out.println(“y=“+y); } }
  • 24. In the previous program we cannot see the value of x just because of the error in the value of y, that is division by zero but when we use the try and catch blocks in exception handling then we can see the value of y which is correct and our program will display an error message shown in the try block.
  • 25. CONCLUSION • Exceptions are a powerful error handling mechanism. • Exceptions in Java are built into the language. • Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws). • Exception handling can only hide the errors. • It cannot correct the errors.
  翻译: