SlideShare a Scribd company logo
Exception Handling Presentation on Presented By : Sumit Lole
Agenda What is Exception? Exception Hierarchy Exception vs. Error Types of Exception Default Exception Handler Exception Handling Creating  Your own Exception
Exception Definition:    “ An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions” An  exception  occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)!
Exception  Hierarchy All exception types are subclasses of the built-in class  Throwable Throwable has two subclasses : Exception  Error
Throwable Error Exception Runtime Exception IO Exception The Java Exception  Hierarchy
Error Error  hierarchy describes internal errors and resource exhaustion.  Don’t throw an object of this type! Relatively rare Mostly beyond programmers control
Types of Exceptions in Java Checked exceptions All exception inherited from Exception Class Unchecked exceptions All exception inherited from RuntimeException Class
Exception handling
Default Exception Handler ? Default handler prints a stack trace from the point at which the exception occurred, and terminates the program Example:  BasicDemo.java
Exception Handling Anticipate the error by the user/system. Return the program to a safe state that enables the user to execute other commands. Inform the user of the error’s cause. Allow the user to save work and terminate the program gracefully.
Ways to throw an Exception Calling a method that throws a  checked exception  Code detects an error and generates  checked exception  with  throw  statement Programming error e.g. a[-1] =0; generates an  unchecked exception   ArrayIndexOutOfBoundsException 4.  JVM or runtime library internal error
Keywords for Java Exceptions throws throw try catch finally
Catching Exceptions “ What goes up must come down” Catching exceptions is a bit trickier An uncaught exception will terminate the program … …  print the exception type to screen … …  print the stack trace.
Using try and catch Placed the code (which is suppose to throw an exception) inside a block of code starting with the “ try ” keyword The  catch  clause should follow immediately the  try  block. Once the  catch  statement has executed, program control continues with the next line in the program following the entire  try/catch  mechanism  Example :  InitialDemo.java
Nested  Try Statement A  try  statement can be inside the block of another try  Each time a  try  statement is entered, the context of that exception is pushed on the stack If an inner  try  statement does not have a catch, then the next  try  statement’s catch handlers are inspected for a match If a method call within a  try  block has  try  block within it, then then it is still nested  try Example :  ExceptionChaining.java
What information does  java.lang.Exception  contain The type of exception   -- the exception class  Where the exception occurred   -- the stack trace  Context and explanatory information   -- the error message, and other state information  Example :  StackTrace.java
finally It is used to handle premature execution of a method (i.e. a method open a file upon entry and closes it upon exit) finally  creates a block of code that will be executed after  try/catch  block has completed and before the code following the  try/catch  block finally  clause will execute whether or not an exception is thrown
Some Important Exception that generally occurs… IOException ClassNotFoundException RuntimeException Most occurring exception Caused by programming error “ If it’s a  RuntimeException  it’s your fault!” Example :  ArrayIndexOutOfBoundException IndexOutOfBound ArithmeticException NullPointerException Example :  ExceptionExample.java
throw It is possible for your program to throw an exception explicitly throw  ExceptionInstance Here,  ExceptionInstance  must be an object of type  Throwable  or a subclass  Throwable There are two ways to obtain a  Throwable  objects: Using a parameter into a catch clause Creating one with the  new  operator
Creating Your Own  Exceptions Java provides over 40 categories of  Exceptions Java allows you to create your own  Exceptions Extend a subclass of  Throwable Exception  class constructors Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause)
Example throw statement :  throw <object reference expression>; Class DivisionByZeroException extends Exception{ DivisionByZeroException(String msg) { super(msg); } } public void division(){ int num1 = 10; int num2 = 0; if(num2 == 0) throw new DivisionByZeroException(); System.out.println(num1/num2); }
throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception type method-name parameter-list)  throws  exception-list { // body of method } It is not applicable for  Error  or  RuntimeException,  or any of their subclasses
Rule for Method Overriding While overriding, the new method definition in the subclass can only specify all or a subset of the exception classes specified in the throws clause of the overridden method in the superclass
Some Methods Inherited from Throwable fillStackTrace() returns Throwable getCause() returns Throwable getMessage() returns String getStackTrace() return StackTraceElement[] - Throwable initCause(Throwable)  printSatckTrace() return void setStackTrace(Throwable)  toString() return String
Queries
Exception handling
Ad

More Related Content

What's hot (20)

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
Kunal Singh
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
myrajendra
 
Presentation1
Presentation1Presentation1
Presentation1
Anul Chaudhary
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 

Viewers also liked (12)

Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
Tata Consultancy Services
 
Exception
ExceptionException
Exception
Марія Русин
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Tcs (tata consultacy services)
Tcs (tata consultacy services)Tcs (tata consultacy services)
Tcs (tata consultacy services)
Nikhil Tiwari
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
Short ppt on TCS !
Short ppt on TCS !Short ppt on TCS !
Short ppt on TCS !
Shanmuga Priya Venkatesan
 
Company Analysis - TCS (Tata Consultancy Services)
Company Analysis - TCS (Tata Consultancy Services)Company Analysis - TCS (Tata Consultancy Services)
Company Analysis - TCS (Tata Consultancy Services)
Kaustubh Barve
 
Ppt on tcs
Ppt on tcsPpt on tcs
Ppt on tcs
Rajnish Deo
 
Tata consultancy services final
Tata consultancy services finalTata consultancy services final
Tata consultancy services final
Wasim Akram
 
Tcs
TcsTcs
Tcs
19Madhuk
 
Ad

Similar to Exception handling (20)

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
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
 
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
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
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
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
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
 
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
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
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
 
Ad

Recently uploaded (20)

One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 

Exception handling

  • 1. Exception Handling Presentation on Presented By : Sumit Lole
  • 2. Agenda What is Exception? Exception Hierarchy Exception vs. Error Types of Exception Default Exception Handler Exception Handling Creating Your own Exception
  • 3. Exception Definition:   “ An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions” An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)!
  • 4. Exception Hierarchy All exception types are subclasses of the built-in class Throwable Throwable has two subclasses : Exception Error
  • 5. Throwable Error Exception Runtime Exception IO Exception The Java Exception Hierarchy
  • 6. Error Error hierarchy describes internal errors and resource exhaustion. Don’t throw an object of this type! Relatively rare Mostly beyond programmers control
  • 7. Types of Exceptions in Java Checked exceptions All exception inherited from Exception Class Unchecked exceptions All exception inherited from RuntimeException Class
  • 9. Default Exception Handler ? Default handler prints a stack trace from the point at which the exception occurred, and terminates the program Example: BasicDemo.java
  • 10. Exception Handling Anticipate the error by the user/system. Return the program to a safe state that enables the user to execute other commands. Inform the user of the error’s cause. Allow the user to save work and terminate the program gracefully.
  • 11. Ways to throw an Exception Calling a method that throws a checked exception Code detects an error and generates checked exception with throw statement Programming error e.g. a[-1] =0; generates an unchecked exception ArrayIndexOutOfBoundsException 4. JVM or runtime library internal error
  • 12. Keywords for Java Exceptions throws throw try catch finally
  • 13. Catching Exceptions “ What goes up must come down” Catching exceptions is a bit trickier An uncaught exception will terminate the program … … print the exception type to screen … … print the stack trace.
  • 14. Using try and catch Placed the code (which is suppose to throw an exception) inside a block of code starting with the “ try ” keyword The catch clause should follow immediately the try block. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism Example : InitialDemo.java
  • 15. Nested Try Statement A try statement can be inside the block of another try Each time a try statement is entered, the context of that exception is pushed on the stack If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match If a method call within a try block has try block within it, then then it is still nested try Example : ExceptionChaining.java
  • 16. What information does java.lang.Exception contain The type of exception -- the exception class Where the exception occurred -- the stack trace Context and explanatory information -- the error message, and other state information Example : StackTrace.java
  • 17. finally It is used to handle premature execution of a method (i.e. a method open a file upon entry and closes it upon exit) finally creates a block of code that will be executed after try/catch block has completed and before the code following the try/catch block finally clause will execute whether or not an exception is thrown
  • 18. Some Important Exception that generally occurs… IOException ClassNotFoundException RuntimeException Most occurring exception Caused by programming error “ If it’s a RuntimeException it’s your fault!” Example : ArrayIndexOutOfBoundException IndexOutOfBound ArithmeticException NullPointerException Example : ExceptionExample.java
  • 19. throw It is possible for your program to throw an exception explicitly throw ExceptionInstance Here, ExceptionInstance must be an object of type Throwable or a subclass Throwable There are two ways to obtain a Throwable objects: Using a parameter into a catch clause Creating one with the new operator
  • 20. Creating Your Own Exceptions Java provides over 40 categories of Exceptions Java allows you to create your own Exceptions Extend a subclass of Throwable Exception class constructors Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause)
  • 21. Example throw statement : throw <object reference expression>; Class DivisionByZeroException extends Exception{ DivisionByZeroException(String msg) { super(msg); } } public void division(){ int num1 = 10; int num2 = 0; if(num2 == 0) throw new DivisionByZeroException(); System.out.println(num1/num2); }
  • 22. throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception type method-name parameter-list) throws exception-list { // body of method } It is not applicable for Error or RuntimeException, or any of their subclasses
  • 23. Rule for Method Overriding While overriding, the new method definition in the subclass can only specify all or a subset of the exception classes specified in the throws clause of the overridden method in the superclass
  • 24. Some Methods Inherited from Throwable fillStackTrace() returns Throwable getCause() returns Throwable getMessage() returns String getStackTrace() return StackTraceElement[] - Throwable initCause(Throwable) printSatckTrace() return void setStackTrace(Throwable) toString() return String

Editor's Notes

  • #8: The first kind of exception is the checked exception . These are exceptional conditions that a well-written application should anticipate and recover from. The second kind of exception is the error . These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses The third kind of exception is the runtime exception . These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API.
  • #11: If you feel that a method doesn&apos;t know how to handle a particular error, you can throw an exception from the method and let someone else deal with it. If you throw a &amp;quot;checked&amp;quot; exception, you enlist the help of the Java compiler to force client programmers to deal with the potential exception, either by catching it or declaring it in the throws clause of their methods.