SlideShare a Scribd company logo
1 of 35
Exception Handling
PRESENTED BY
S.KARTHIK
ASSISTANT PROFESSOR OF IT
PSG COLLEGE OF ARTS & SCIENCE
COIMBATORE - 14
Why??
 An Error is any unexpected result obtained from a program during execution.
 Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal
program termination.
 Errors should be handled by the programmer, to prevent them from reaching the user.
 When a program runs into a runtime error, the program terminates abnormally.
 How can you handle the runtime error so that the program can continue to run or terminate
gracefully?
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)
• Unexpected conditions
• Disrupt normal flow of program
• With exception handling, we can develop more robust programs
Exceptions
Exceptions
Exceptions are thrown
And can be caught.
How do you handle exceptions?
Exception handling is accomplished through
the “try – catch” mechanism, or by a “throws”
clause in the method declaration.
For any code that throws a checked
exception, you can decide to handle the
exception yourself, or pass the exception “up
the chain” (to a parent class).
Where do exceptions come from?
• JVM
OR
• Java Programs – can throw an exception
 What are they?
 An exception is a representation of an error condition or a situation that is not
the expected result of a method.
 Exceptions are built into the Java language and are available to all program
code.
 Exceptions isolate the code that deals with the error condition from regular
program logic.
Exception Types
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System Errors
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
Runtime Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-
bounds array, and numeric
errors.
Types of Exceptions
• Errors - serious and fatal problems
• Exceptions - can be thrown by any program, user can extend
• RuntimException - caused by illegal operations, thrown by JVM
(unchecked)
Checked Exceptions vs.
Unchecked Exceptions
RuntimeException, Error and their subclasses are known as unchecked
exceptions.
All other exceptions are known as checked exceptions - the compiler
forces the programmer to check and deal with the exceptions.
Checked or Unchecked Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Unchecked
exception.
Declaring, Throwing, and Catching
Exceptions
method1() {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
}
method2() throws Exception {
if (an error occurs) {
throw new Exception();
}
}
catch exception throwexception
declare exception
Checked Exceptions
Checked exceptions that can be thrown in a method must be
• caught and handled
OR
• declared in the throws clause
Declaring Exceptions
Every method must state the types of checked exceptions it might
throw. This is known as declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
Throwing Exceptions
When the program detects an error, the program can create an
instance of an appropriate exception type and throw it. This is known
as throwing an exception. Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Catching Exceptions
try
catch
try
catch
try
catch
An exception
is thrown in
method3
Call Stack
main method main method
method1
main method
method1
main method
method1
method2 method2
method3
Catch or Declare Checked Exceptions
If a method declares a checked exception, you must invoke it in a try-catch block or declare
to throw the exception in the calling method.
In this example, method p1 invokes method p2 and p2 may throw a checked exception
(e.g., IOException)
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
(a) (b)
void p1() throws IOException {
p2();
}
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Suppose no
exceptions in the
statements
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block is
always executed
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next Statement;
Next statement;
Next statement in the
method is executed
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
statement2 throws an
exception of type
Exception2.
Trace a Program Execution
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Handling exception
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Execute the final block
Cautions When Using Exceptions
• Exception handling separates error-handling code from normal
programming tasks, thus making programs easier to read and to
modify.
• Exception handling usually requires more time and resources because
it requires instantiating a new exception object, rolling back the call
stack, and propagating the errors to the calling methods.
When to Throw Exceptions
• An exception occurs in a method.
• If you want the exception to be processed by its caller, you should
create an exception object and throw it.
• If you can handle the exception in the method where it occurs, there
is no need to throw it.
When to Use Exceptions
When should you use the try-catch block in the code? You should use it
to deal with unexpected error conditions. Do not use it to deal with
simple, expected situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
Creating Custom Exception Classes
 Use the exception classes in the API whenever possible.
 Create custom exception classes if the predefined classes are not sufficient.
 Declare custom exception classes by extending Exception or a subclass of
Exception.
Exceptions and Inheritance
How do you think exceptions affect overridden methods?
• if a method overrides a base class method, the new method cannot
throw a more general error, but can throw more specific.
• if the base class method throws no errors, the subclass method can't
either.
Thank You

More Related Content

What's hot (20)

Exception handling
Exception handling Exception handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 

Similar to Exception handling

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertionsphanleson
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1Shinu Suresh
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
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 MultithreadingSakkaravarthiS1
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 

Similar to Exception handling (20)

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertions
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
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
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 

Recently uploaded

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 

Recently uploaded (20)

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 

Exception handling

  • 1. Exception Handling PRESENTED BY S.KARTHIK ASSISTANT PROFESSOR OF IT PSG COLLEGE OF ARTS & SCIENCE COIMBATORE - 14
  • 2. Why??  An Error is any unexpected result obtained from a program during execution.  Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination.  Errors should be handled by the programmer, to prevent them from reaching the user.  When a program runs into a runtime error, the program terminates abnormally.  How can you handle the runtime error so that the program can continue to run or terminate gracefully?
  • 3. 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)
  • 4. • Unexpected conditions • Disrupt normal flow of program • With exception handling, we can develop more robust programs Exceptions
  • 5. Exceptions Exceptions are thrown And can be caught. How do you handle exceptions? Exception handling is accomplished through the “try – catch” mechanism, or by a “throws” clause in the method declaration. For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).
  • 6. Where do exceptions come from? • JVM OR • Java Programs – can throw an exception  What are they?  An exception is a representation of an error condition or a situation that is not the expected result of a method.  Exceptions are built into the Java language and are available to all program code.  Exceptions isolate the code that deals with the error condition from regular program logic.
  • 8. System Errors LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
  • 9. Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
  • 10. Runtime Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException RuntimeException is caused by programming errors, such as bad casting, accessing an out-of- bounds array, and numeric errors.
  • 11. Types of Exceptions • Errors - serious and fatal problems • Exceptions - can be thrown by any program, user can extend • RuntimException - caused by illegal operations, thrown by JVM (unchecked)
  • 12. Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions - the compiler forces the programmer to check and deal with the exceptions.
  • 13. Checked or Unchecked Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Unchecked exception.
  • 14. Declaring, Throwing, and Catching Exceptions method1() { try { invoke method2; } catch (Exception ex) { Process exception; } } method2() throws Exception { if (an error occurs) { throw new Exception(); } } catch exception throwexception declare exception
  • 15. Checked Exceptions Checked exceptions that can be thrown in a method must be • caught and handled OR • declared in the throws clause
  • 16. Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException
  • 17. Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex;
  • 18. Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
  • 19. Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; }
  • 20. Catching Exceptions try catch try catch try catch An exception is thrown in method3 Call Stack main method main method method1 main method method1 main method method1 method2 method2 method3
  • 21. Catch or Declare Checked Exceptions If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method. In this example, method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException) void p1() { try { p2(); } catch (IOException ex) { ... } } (a) (b) void p1() throws IOException { p2(); }
  • 22. The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; }
  • 23. Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements
  • 24. Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
  • 25. Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next Statement; Next statement; Next statement in the method is executed
  • 26. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } statement2 throws an exception of type Exception2. Trace a Program Execution
  • 27. Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Handling exception
  • 28. Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Execute the final block
  • 29. Cautions When Using Exceptions • Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. • Exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.
  • 30. When to Throw Exceptions • An exception occurs in a method. • If you want the exception to be processed by its caller, you should create an exception object and throw it. • If you can handle the exception in the method where it occurs, there is no need to throw it.
  • 31. When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }
  • 32. When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");
  • 33. Creating Custom Exception Classes  Use the exception classes in the API whenever possible.  Create custom exception classes if the predefined classes are not sufficient.  Declare custom exception classes by extending Exception or a subclass of Exception.
  • 34. Exceptions and Inheritance How do you think exceptions affect overridden methods? • if a method overrides a base class method, the new method cannot throw a more general error, but can throw more specific. • if the base class method throws no errors, the subclass method can't either.