SlideShare a Scribd company logo
Exceptions in Java




                     Author: Vadim Lotar
                     Lohika (2011)
Agenda


 •   Introduction
 •   Errors and Error handling
 •   Exceptions
 •   Types of Exceptions
 •   Keywords
 •   Exceptions handling
 •   Summary
Introduction
 •   Customers have high expectations for the code we
     produce.
 •   Users will use our programs in unexpected ways.
 •   Due to design errors or coding errors, our
     programs may fail in unexpected ways during
     execution
 •   It is our responsibility to produce quality code that
     does not fail unexpectedly.
 •   Consequently, we must design error handling into
     our programs.
Errors and Error handling
 •   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.
Errors and Error handling
 •   Memory errors (i.e memory incorrectly allocated,
     memory leaks…)
 •   File system errors (i.e. disk is full…)
 •   Network errors (i.e. network is down…)
 •   Calculation errors (i.e. divide by 0)
 •   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
 •   Every method returns a value (flag)
     indicating either success, failure, or some
     error condition.
 •   Cons: developer must remember to
     always check the return value and take
     appropriate action.
 •   Where used: traditional programming
     languages (i.e. C) use this method for almost
     all library functions
Errors and Error handling
 •   Create a global error handling routine,
     and use some form of “jump” instruction
     to call this routine when an error occurs
 •   Cons: “jump” instruction (GoTo) are
     considered “bad programming practice”
     and are discouraged
 •   Where used: many older programming texts
     (C, FORTRAN) recommended this method to
     programmers.
Exceptions
Exceptions

 •   Exceptions – a better error handling
 •   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.
Types of Exceptions
•   Unchecked Exceptions                  •   Checked Exceptions
    It is not required that these types       Must either be caught by a
    of exceptions be caught or                method or declared in its
    declared on a method.                     signature.

    •   Runtime exceptions can be             •   Placing exceptions in the
        generated by methods or by                method signature harkens
        the JVM itself.                           back to a major concern for
                                                  Goodenough.
    •   Errors are generated from
        deep within the JVM, and              •   This requirement is viewed
        often indicate a truly fatal              with derision in the
        state.                                    hardcore C++ community.

    •   Runtime exceptions are a              •   A common technique for
        source of major controversy!              simplifying checked
                                                  exceptions is subsumption.
Types of Exceptions
  Throwable               The base class for all exceptions.



  Error                   Indicates serious problems that a reasonable application
                          should not try to catch. Most such errors are abnormal
                          conditions.
  Exception               Anything which should be handled by the invoker.




                                                java.lang.Throwable


    java.lang.Error                                               java.lang.Exception


 java.lang.ThreadDeath             java.lang.RuntimeException                                java.io.IOException


               java.lang.NullPointerException    java.lang.IllegalArgumentException     java.io.FileNotFoundException
Types of Exceptions

    •    Three Critical Decisions:
•   How do you decide to raise an exception rather than return?
        1. Is the situation truly out of the ordinary?
        2. Should it be impossible for the caller to ignore this problem?
        3. Does this situation render the class unstable or inconsistent?

•   Should you reuse an existing exception or create a new type?
        1. Can you map this to an existing exception class?
        2. Is the checked/unchecked status of mapped exception acceptable?
        3. Are you masking many possible exceptions for a more general one?

•   How do you deal with subsumption in a rich exception hierarchy?
        1. Avoid throwing a common base class (e.g. IOException).
        2. Never throw an instance of the Exception or Throwable classes.
Keywords
 •   throws
     Describes the exceptions which can be raised by a method.

 •   throw
     Raises an exception to the first available handler in the call
     stack, unwinding the stack along the way.

 •   try
     Marks the start of a block associated with a set of exception
     handlers.

 •   catch
     If the block enclosed by the try generates an exception of this
     type, control moves here; watch out for implicit subsumption.

 •   finally
     Always called when the try block concludes, and after any
     necessary catch handler is complete.
Keywords
 public void setProperty(String p_strValue) throws
    NullPointerException
 {
    if (p_strValue == null) {throw new NullPointerException(“...”);}
 }

 public void myMethod() {
    MyClass oClass = new MyClass();

     try {
       oClass.setProperty(“foo”);
       oClass.doSomeWork();

     } catch (NullPointerException npe) {
       System.err.println(“Unable to set property: “+npe.toString());
     } finally {
       oClass.cleanup();
     }
 }
Keywords
 •   throw(s)
 /* The IllegalArgumentException is considered unchecked, and
  * even making it part of the signature will not alter that. */
 public void setName(String p_strName) throws
    IllegalArgumentException
 {
    /* valid names cannot be zero length */
    if (p_strName.length() == 0) {
      throw new IllegalArgumentException(“…”);
    }
    m_strName = p_strName;
 }

 public void foo() {
    setName(“”); /* No warning about unhandled exceptions. */
 }
Keywords
 •   throw(s)
 /* Make a bad parameter exception class */
 class NuttyParameterException extends Exception { … }

 /* To really make an invoker pay attention, use a checked
  * exception type rather than a Runtime Exception type, but you
    must declare that you will throw the type! */
 public void setName(String p_strName)
                                 throws NuttyParameterException
 {
    /* valid names cannot be zero length */
    if (p_strName == null || p_strName.length() == 0) {
      throw new NuttyParameterException(“…”);
    }
    m_strName = p_strName;
 }
 /* Many of us will have an unquenchable desire to use a Runtime
  * exception in the above, but resist! */
 public void foo() {
    setName(“”); /* This does result in an error. */
 }
Keywords
 •   try
 /* The try statement marks the position of the first bytecode
    instruction
  * protected by an exception handler. */
 try {
    UserRecord oUser = new UserRecord();
    oUser.setName(“Mr. XXX”);
    oUser.store();

 /* This catch statement then marks the final bytecode
    instruction protected, and begins the list of exceptions
    handled. This info is collected and is stored in the
    exception table for the method. */
 } catch (CreateException ce) {
    System.err.println(“Unable to create user record in the
    database.”);
 }
Keywords
 •   catch
 /* A simple use of a catch block is to catch the exception
    raised by the code from a prior slide. */
 try {
    myObject.setName(“foo”);
 } catch (NuttyParameterException npe) {
    System.err.println(“Unable to assign name: “ +
    npe.toString());
 }

 try { /* example 2 */
    myObject.setName(“foo”);
 } catch (NuttyParameterException npe) { /* log and relay this
    problem. */
    System.err.println(“Unable to assign name: “ +
    npe.toString());
    throw npe;
 }
Keywords
 •   catch
 /* Several catch blocks of differing types can be concatenated.
    */
  try {
    URL myURL = new URL("http://www.mainejug.org");
    InputStream oStream = myURL.openStream();
    byte[] myBuffer = new byte[512];
    int nCount = 0;

     while ((nCount = oStream.read(myBuffer)) != -1) {
       System.out.println(new String(myBuffer, 0, nCount));
     }
     oStream.close();

 } catch (MalformedURLException mue) {
    System.err.println("MUE: " + mue.toString());
 } catch (IOException ioe) {
    System.err.println("IOE: " + ioe.toString());
 }
Keywords
 •   finally
 URL myURL = null;
 InputStream oStream = null;
 /* The prior sample completely neglected to discard the network
  * resources, remember that the GC is non-determinstic!! */
 try {
    /* Imagine you can see the code from the last slide here...
    */

 } finally { /* What two things can cause a finally block to be
    missed? */
    /* Since we cannot know when the exception occurred, be
    careful! */
      try {
         oStream.close();
      } catch (Exception e) {
    }
 }
Keywords
 •   finally
 public boolean anotherMethod(Object myParameter) {

     try { /* What value does this snippet return? */
       myClass.myMethod(myParameter);
       return true;

     } catch (Exception e) {
       System.err.println(“Exception in anotherMethod()“
                                         +e.toString());
       return false;

     } finally {
       /* If the close operation can raise an exception,
       whoops! */
       if (myClass.close() == false) {
              break;
       }                                             1. True
     }                                               2. False
     return false;
 }
                                                      3. An exception
                                                      4. Non of above
Keywords
 •   finally
 public void callMethodSafely() {

     while (true) { /* How about this situation? */
       try {
              /* Call this method until it returns false.
              */
              if (callThisOTherMethod() == false) {
                     return;
              }

       } finally {                                 1.   Infinite loop
              continue;                            2.   1
       }                                           3.   2
     } /* end of while */                          4.   An exception
 }

 public boolean callThisOTherMethod() {
    return false;
 }
Practice
 /* Since UnknownHostException extends IOException, the
    catch block associated with the former is subsumed. */
 try {
    Socket oConn = new Socket(“www.sun.com”, 80);
 } catch (IOException ioe) {
 } catch (UnknownHostException ohe) {
 }




 /* The correct structure is to arrange the catch blocks
    with the most derived class first, and base class at
    the bottom. */
 try {
    Socket oConn = new Socket(“www.sun.com”, 80);
 } catch (UnknownHostException ohe) {
 } catch (IOException ioe) {
 }
Practice
 class MyThread implements Runnable {
    public MyTask m_oTask = null;
    public void run() {
      if (m_oTask == null) {
        throw new IllegalStateException(“No work to be
    performed!”);
      } else {
        /* Do the work of the thread. */
      }
    }
 }

 public void foo() {
    MyThread oThread = new MyThread();
    /* There is no way to get the exception from the run()
    method! */
    new Thread(oThread).start();
    /* Good reason for Runtime choice!! */
 }
Practice
 public interface ITest {
     void test() throws IOException ;
 }

 public class TestImpl implements ITest{

     public void test() throws IOException, InvalidArgumentException {
        //some code
     }

     public void test() throws IOException, FileNotFoundException {
        //some code
     }

     public void test() {
        //some code
     }

     public void test() throws IOException {
        //some code
     }
 }
New in Java 7
} catch (FirstException ex) {           Multi-catch feature
    logger.error(ex);                   } catch (FirstException | SecondException ex) {
    throw ex;                               logger.error(ex);
} catch (SecondException ex) {              throw ex;
    logger.error(ex);                   }
    throw ex;
}


Final rethrow
public static void test2() throws ParseException, IOException{
  DateFormat df = new SimpleDateFormat("yyyyMMdd");
  try {
     df.parse("x20110731");
     new FileReader("file.txt").read();
  } catch (final Exception e) {
     System.out.println("Caught exception: " + e.getMessage());
     throw e;
  }
}
New in Java 7
 public class OldTry {
      public static void main(String[] args) {
         OldResource res = null;
         try {
             res = new OldResource();
             res.doSomeWork("Writing an article");
         } catch (Exception e) {
             System.out.println("Exception Message: " +
                   e.getMessage() + " Exception Type: " + e.getClass().getName());
         } finally {
             try {
                res.close();
             } catch (Exception e) {
                System.out.println("Exception Message: " +
                      e.getMessage() + " Exception Type: " + e.getClass().getName());
             }
         }
      }
   }

 public class TryWithRes {
     public static void main(String[] args) {
         try(NewResource res = new NewResource("Res1 closing")){
             res.doSomeWork("Listening to podcast");
         } catch(Exception e){
             System.out.println("Exception: "+
        e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());
         }
     }
 }
Summary

 •   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).
Q&A
Task
 •   Implement Application
     •   App takes two parameters from the command
         line: the directory path and a file name.
     •   App should have an ability to find the file in
         sub folders too.
     •   Read data from file and print it
     •   Every possible error situation should be
         handled
         •   Create an own class which represents an
             exception

More Related Content

What's hot (20)

PPTX
Exception handling in java
ARAFAT ISLAM
 
PPTX
Strings in Java
Abhilash Nair
 
PPTX
Exception handling in java
Elizabeth alexander
 
PPTX
Spring Boot
Jiayun Zhou
 
PPS
Wrapper class
kamal kotecha
 
PPT
Collection Framework in java
CPD INDIA
 
PPTX
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPTX
Exception handling
PhD Research Scholar
 
PPTX
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
PPTX
Exception handling in Java
Ankit Rai
 
PPTX
Exceptional Handling in Java
QaziUmarF786
 
PPT
Spring Boot in Action
Alex Movila
 
PPT
Generics in java
suraj pandey
 
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
PDF
Java logging
Jumping Bean
 
PPTX
Java beans
Rajkiran Mummadi
 
PPS
Java Exception handling
kamal kotecha
 
PPT
Java interfaces & abstract classes
Shreyans Pathak
 
Exception handling in java
ARAFAT ISLAM
 
Strings in Java
Abhilash Nair
 
Exception handling in java
Elizabeth alexander
 
Spring Boot
Jiayun Zhou
 
Wrapper class
kamal kotecha
 
Collection Framework in java
CPD INDIA
 
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Core java complete ppt(note)
arvind pandey
 
Exception handling
PhD Research Scholar
 
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Exception handling in Java
Ankit Rai
 
Exceptional Handling in Java
QaziUmarF786
 
Spring Boot in Action
Alex Movila
 
Generics in java
suraj pandey
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Java logging
Jumping Bean
 
Java beans
Rajkiran Mummadi
 
Java Exception handling
kamal kotecha
 
Java interfaces & abstract classes
Shreyans Pathak
 

Viewers also liked (20)

PPTX
Log management (elk) for spring boot application
Vadym Lotar
 
PPTX
Java - Exception Handling
Prabhdeep Singh
 
PPT
Java: Exception
Tareq Hasan
 
PPT
Exception handling in java
Pratik Soares
 
PDF
Java exception handling ppt
JavabynataraJ
 
PPT
9781111530532 ppt ch11
Terry Yoast
 
PPTX
Lecture 22
talha ijaz
 
PPT
7 streams and error handling in java
Jyoti Verma
 
PPT
Real-time Programming in Java
Aleš Plšek
 
PPT
Runnable interface.34
myrajendra
 
PPT
Exception handling
Iblesoft
 
PPT
Access Protection
myrajendra
 
PPT
Java exception
Arati Gadgil
 
PPTX
Effective Java - Chapter 4: Classes and Interfaces
İbrahim Kürce
 
PDF
JBoss Fuse - Fuse workshop Error Handling
Christina Lin
 
PDF
Improve business process with microservice integration
Christina Lin
 
PPT
Exception Handling Java
ankitgarg_er
 
PPTX
Exception handling in asp.net
Neelesh Shukla
 
PDF
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
PDF
Java keywords
Ravi_Kant_Sahu
 
Log management (elk) for spring boot application
Vadym Lotar
 
Java - Exception Handling
Prabhdeep Singh
 
Java: Exception
Tareq Hasan
 
Exception handling in java
Pratik Soares
 
Java exception handling ppt
JavabynataraJ
 
9781111530532 ppt ch11
Terry Yoast
 
Lecture 22
talha ijaz
 
7 streams and error handling in java
Jyoti Verma
 
Real-time Programming in Java
Aleš Plšek
 
Runnable interface.34
myrajendra
 
Exception handling
Iblesoft
 
Access Protection
myrajendra
 
Java exception
Arati Gadgil
 
Effective Java - Chapter 4: Classes and Interfaces
İbrahim Kürce
 
JBoss Fuse - Fuse workshop Error Handling
Christina Lin
 
Improve business process with microservice integration
Christina Lin
 
Exception Handling Java
ankitgarg_er
 
Exception handling in asp.net
Neelesh Shukla
 
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
Java keywords
Ravi_Kant_Sahu
 
Ad

Similar to Exceptions in Java (20)

PPTX
UNIT III 2021R.pptx
RDeepa9
 
PPTX
UNIT III 2021R.pptx
RDeepa9
 
PDF
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
PPTX
Introduction to java exceptions
Sujit Kumar
 
PPTX
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
PPTX
Java-Unit 3- Chap2 exception handling
raksharao
 
PPTX
Chap2 exception handling
raksharao
 
PPTX
Exceptions overview
Bharath K
 
PPT
Exception handling
pooja kumari
 
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
PPT
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
PPT
Exception handling
Karthik Sekar
 
PPTX
Java Exceptions and Exception Handling
MaqdamYasir
 
PPTX
Exception handling in .net
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
PPTX
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
PPT
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
PPTX
Training material exceptions v1
Shinu Suresh
 
PPT
Exception
abhay singh
 
PPTX
Java exception handling
GaneshKumarKanthiah
 
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
RDeepa9
 
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Introduction to java exceptions
Sujit Kumar
 
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Java-Unit 3- Chap2 exception handling
raksharao
 
Chap2 exception handling
raksharao
 
Exceptions overview
Bharath K
 
Exception handling
pooja kumari
 
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Exception handling
Karthik Sekar
 
Java Exceptions and Exception Handling
MaqdamYasir
 
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Training material exceptions v1
Shinu Suresh
 
Exception
abhay singh
 
Java exception handling
GaneshKumarKanthiah
 
Ad

Recently uploaded (20)

PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 

Exceptions in Java

  • 1. Exceptions in Java Author: Vadim Lotar Lohika (2011)
  • 2. Agenda • Introduction • Errors and Error handling • Exceptions • Types of Exceptions • Keywords • Exceptions handling • Summary
  • 3. Introduction • Customers have high expectations for the code we produce. • Users will use our programs in unexpected ways. • Due to design errors or coding errors, our programs may fail in unexpected ways during execution • It is our responsibility to produce quality code that does not fail unexpectedly. • Consequently, we must design error handling into our programs.
  • 4. Errors and Error handling • 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.
  • 5. Errors and Error handling • Memory errors (i.e memory incorrectly allocated, memory leaks…) • File system errors (i.e. disk is full…) • Network errors (i.e. network is down…) • Calculation errors (i.e. divide by 0) • Array errors (i.e. accessing element –1) • Conversion errors (i.e. convert „q‟ to a number) • Can you think of some others?
  • 6. Errors and Error handling • Every method returns a value (flag) indicating either success, failure, or some error condition. • Cons: developer must remember to always check the return value and take appropriate action. • Where used: traditional programming languages (i.e. C) use this method for almost all library functions
  • 7. Errors and Error handling • Create a global error handling routine, and use some form of “jump” instruction to call this routine when an error occurs • Cons: “jump” instruction (GoTo) are considered “bad programming practice” and are discouraged • Where used: many older programming texts (C, FORTRAN) recommended this method to programmers.
  • 9. Exceptions • Exceptions – a better error handling • 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.
  • 10. Types of Exceptions • Unchecked Exceptions • Checked Exceptions It is not required that these types Must either be caught by a of exceptions be caught or method or declared in its declared on a method. signature. • Runtime exceptions can be • Placing exceptions in the generated by methods or by method signature harkens the JVM itself. back to a major concern for Goodenough. • Errors are generated from deep within the JVM, and • This requirement is viewed often indicate a truly fatal with derision in the state. hardcore C++ community. • Runtime exceptions are a • A common technique for source of major controversy! simplifying checked exceptions is subsumption.
  • 11. Types of Exceptions Throwable The base class for all exceptions. Error Indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Exception Anything which should be handled by the invoker. java.lang.Throwable java.lang.Error java.lang.Exception java.lang.ThreadDeath java.lang.RuntimeException java.io.IOException java.lang.NullPointerException java.lang.IllegalArgumentException java.io.FileNotFoundException
  • 12. Types of Exceptions • Three Critical Decisions: • How do you decide to raise an exception rather than return? 1. Is the situation truly out of the ordinary? 2. Should it be impossible for the caller to ignore this problem? 3. Does this situation render the class unstable or inconsistent? • Should you reuse an existing exception or create a new type? 1. Can you map this to an existing exception class? 2. Is the checked/unchecked status of mapped exception acceptable? 3. Are you masking many possible exceptions for a more general one? • How do you deal with subsumption in a rich exception hierarchy? 1. Avoid throwing a common base class (e.g. IOException). 2. Never throw an instance of the Exception or Throwable classes.
  • 13. Keywords • throws Describes the exceptions which can be raised by a method. • throw Raises an exception to the first available handler in the call stack, unwinding the stack along the way. • try Marks the start of a block associated with a set of exception handlers. • catch If the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption. • finally Always called when the try block concludes, and after any necessary catch handler is complete.
  • 14. Keywords public void setProperty(String p_strValue) throws NullPointerException { if (p_strValue == null) {throw new NullPointerException(“...”);} } public void myMethod() { MyClass oClass = new MyClass(); try { oClass.setProperty(“foo”); oClass.doSomeWork(); } catch (NullPointerException npe) { System.err.println(“Unable to set property: “+npe.toString()); } finally { oClass.cleanup(); } }
  • 15. Keywords • throw(s) /* The IllegalArgumentException is considered unchecked, and * even making it part of the signature will not alter that. */ public void setName(String p_strName) throws IllegalArgumentException { /* valid names cannot be zero length */ if (p_strName.length() == 0) { throw new IllegalArgumentException(“…”); } m_strName = p_strName; } public void foo() { setName(“”); /* No warning about unhandled exceptions. */ }
  • 16. Keywords • throw(s) /* Make a bad parameter exception class */ class NuttyParameterException extends Exception { … } /* To really make an invoker pay attention, use a checked * exception type rather than a Runtime Exception type, but you must declare that you will throw the type! */ public void setName(String p_strName) throws NuttyParameterException { /* valid names cannot be zero length */ if (p_strName == null || p_strName.length() == 0) { throw new NuttyParameterException(“…”); } m_strName = p_strName; } /* Many of us will have an unquenchable desire to use a Runtime * exception in the above, but resist! */ public void foo() { setName(“”); /* This does result in an error. */ }
  • 17. Keywords • try /* The try statement marks the position of the first bytecode instruction * protected by an exception handler. */ try { UserRecord oUser = new UserRecord(); oUser.setName(“Mr. XXX”); oUser.store(); /* This catch statement then marks the final bytecode instruction protected, and begins the list of exceptions handled. This info is collected and is stored in the exception table for the method. */ } catch (CreateException ce) { System.err.println(“Unable to create user record in the database.”); }
  • 18. Keywords • catch /* A simple use of a catch block is to catch the exception raised by the code from a prior slide. */ try { myObject.setName(“foo”); } catch (NuttyParameterException npe) { System.err.println(“Unable to assign name: “ + npe.toString()); } try { /* example 2 */ myObject.setName(“foo”); } catch (NuttyParameterException npe) { /* log and relay this problem. */ System.err.println(“Unable to assign name: “ + npe.toString()); throw npe; }
  • 19. Keywords • catch /* Several catch blocks of differing types can be concatenated. */ try { URL myURL = new URL("http://www.mainejug.org"); InputStream oStream = myURL.openStream(); byte[] myBuffer = new byte[512]; int nCount = 0; while ((nCount = oStream.read(myBuffer)) != -1) { System.out.println(new String(myBuffer, 0, nCount)); } oStream.close(); } catch (MalformedURLException mue) { System.err.println("MUE: " + mue.toString()); } catch (IOException ioe) { System.err.println("IOE: " + ioe.toString()); }
  • 20. Keywords • finally URL myURL = null; InputStream oStream = null; /* The prior sample completely neglected to discard the network * resources, remember that the GC is non-determinstic!! */ try { /* Imagine you can see the code from the last slide here... */ } finally { /* What two things can cause a finally block to be missed? */ /* Since we cannot know when the exception occurred, be careful! */ try { oStream.close(); } catch (Exception e) { } }
  • 21. Keywords • finally public boolean anotherMethod(Object myParameter) { try { /* What value does this snippet return? */ myClass.myMethod(myParameter); return true; } catch (Exception e) { System.err.println(“Exception in anotherMethod()“ +e.toString()); return false; } finally { /* If the close operation can raise an exception, whoops! */ if (myClass.close() == false) { break; } 1. True } 2. False return false; } 3. An exception 4. Non of above
  • 22. Keywords • finally public void callMethodSafely() { while (true) { /* How about this situation? */ try { /* Call this method until it returns false. */ if (callThisOTherMethod() == false) { return; } } finally { 1. Infinite loop continue; 2. 1 } 3. 2 } /* end of while */ 4. An exception } public boolean callThisOTherMethod() { return false; }
  • 23. Practice /* Since UnknownHostException extends IOException, the catch block associated with the former is subsumed. */ try { Socket oConn = new Socket(“www.sun.com”, 80); } catch (IOException ioe) { } catch (UnknownHostException ohe) { } /* The correct structure is to arrange the catch blocks with the most derived class first, and base class at the bottom. */ try { Socket oConn = new Socket(“www.sun.com”, 80); } catch (UnknownHostException ohe) { } catch (IOException ioe) { }
  • 24. Practice class MyThread implements Runnable { public MyTask m_oTask = null; public void run() { if (m_oTask == null) { throw new IllegalStateException(“No work to be performed!”); } else { /* Do the work of the thread. */ } } } public void foo() { MyThread oThread = new MyThread(); /* There is no way to get the exception from the run() method! */ new Thread(oThread).start(); /* Good reason for Runtime choice!! */ }
  • 25. Practice public interface ITest { void test() throws IOException ; } public class TestImpl implements ITest{ public void test() throws IOException, InvalidArgumentException { //some code } public void test() throws IOException, FileNotFoundException { //some code } public void test() { //some code } public void test() throws IOException { //some code } }
  • 26. New in Java 7 } catch (FirstException ex) { Multi-catch feature logger.error(ex); } catch (FirstException | SecondException ex) { throw ex; logger.error(ex); } catch (SecondException ex) { throw ex; logger.error(ex); } throw ex; } Final rethrow public static void test2() throws ParseException, IOException{ DateFormat df = new SimpleDateFormat("yyyyMMdd"); try { df.parse("x20110731"); new FileReader("file.txt").read(); } catch (final Exception e) { System.out.println("Caught exception: " + e.getMessage()); throw e; } }
  • 27. New in Java 7 public class OldTry { public static void main(String[] args) { OldResource res = null; try { res = new OldResource(); res.doSomeWork("Writing an article"); } catch (Exception e) { System.out.println("Exception Message: " + e.getMessage() + " Exception Type: " + e.getClass().getName()); } finally { try { res.close(); } catch (Exception e) { System.out.println("Exception Message: " + e.getMessage() + " Exception Type: " + e.getClass().getName()); } } } } public class TryWithRes { public static void main(String[] args) { try(NewResource res = new NewResource("Res1 closing")){ res.doSomeWork("Listening to podcast"); } catch(Exception e){ System.out.println("Exception: "+ e.getMessage()+" Thrown by: "+e.getClass().getSimpleName()); } } }
  • 28. Summary • 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).
  • 29. Q&A
  • 30. Task • Implement Application • App takes two parameters from the command line: the directory path and a file name. • App should have an ability to find the file in sub folders too. • Read data from file and print it • Every possible error situation should be handled • Create an own class which represents an exception

Editor's Notes

  • #6: NPEDisk has been removedURL does not exist. Socket exception
  • #8: Once you jump to the error routine, you cannot return to the point of origin and so must (probably) exit the program.Those who use this method will frequently adapt it to new languages (C++, Java).
  • #10: 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.
  • #11: How are they used?Exceptions fall into two categories:Checked ExceptionsUnchecked ExceptionsChecked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program executionChecked exceptions must be handled in your code, or passed to parent classes for handling.How are they used?Unchecked exceptions represent error conditions that are considered “fatal” to program execution.You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error messageExamples:Checked exceptions include errors such as “array index out of bounds”, “file not found” and “number format conversion”.Unchecked exceptions include errors such as “null pointer”.Runtime exceptions make it impossible to know what exceptions can be emitted by a method. They also result in incosistent throws decls among developers.Describe subsumption to people: subsumption is often how IOException derivatives are dealt with (subsumption is casting to the base class).The most vituperative debate is between those who believe unchecked exceptions make mechanical testing nearly impossible, and those who believe that checked exceptions impinge on polymorphism by making the exception list part of the method signature (and thereby inheritable).
  • #12: Creating your own exception class
  • #13: Creating your own exception classWhen you attempt to map your situation onto an existing Exception class consider these suggestions:Avoid using an unchecked exception, if it is important enough to explicitly throw, it is important enough to be caught.Never throw a base exception class if you can avoid it: RuntimeException, IOException, RemoteException, etc.Be certain your semantics really match. For example, javax.transaction.TransactionRolledBackException, should not be raised by your JDBC code.There is no situation which should cause you to throw the Exception or Throwable base classes. Never.Use unchecked exceptions to indicate a broken contract:public void setName(String p_strName) { /* This is a violated precondition. */ if (p_strName == null || p_strName.length() == 0) { throw new InvalidArgumentException(“Name parameter invalid!”); }}
  • #27: Using the final keyword it allows you to throw an exception of the exact dynamic type that will be throwed. So if an IOException occurs, an IOException will be throwed. Of course, you have to declare the exceptions not caught. You throws clauses will exactly the same if you use the code (in //some code) without catching anything but now you can do something if that happens.I think multi-catch is a great feature, but for me the final rethrow is not often useful for programmers and perhaps a little weird using the final keyword.
  • #28: Using the final keyword it allows you to throw an exception of the exact dynamic type that will be throwed. So if an IOException occurs, an IOException will be throwed. Of course, you have to declare the exceptions not caught. You throws clauses will exactly the same if you use the code (in //some code) without catching anything but now you can do something if that happens.I think multi-catch is a great feature, but for me the final rethrow is not often useful for programmers and perhaps a little weird using the final keyword.
  • #29: Do not use exceptions to manage flow of control: exit a loop with a status variable rather than raising an exception.