SlideShare uma empresa Scribd logo
1 de 30
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

Mais conteúdo relacionado

Mais procurados

Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In JavaCharthaGaglani
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streamsbabak danyal
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 

Mais procurados (20)

Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Applets
AppletsApplets
Applets
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 

Destaque

Log management (elk) for spring boot application
Log management (elk) for spring boot applicationLog management (elk) for spring boot application
Log management (elk) for spring boot applicationVadym Lotar
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11Terry Yoast
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in javaJyoti Verma
 
Real-time Programming in Java
Real-time Programming in JavaReal-time Programming in Java
Real-time Programming in JavaAleš Plšek
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Access Protection
Access ProtectionAccess Protection
Access Protectionmyrajendra
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfacesİbrahim Kürce
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingChristina Lin
 
Improve business process with microservice integration
Improve business process with microservice integration �Improve business process with microservice integration �
Improve business process with microservice integration Christina Lin
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.netNeelesh Shukla
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Angelin R
 

Destaque (20)

Log management (elk) for spring boot application
Log management (elk) for spring boot applicationLog management (elk) for spring boot application
Log management (elk) for spring boot application
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
 
Real-time Programming in Java
Real-time Programming in JavaReal-time Programming in Java
Real-time Programming in Java
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Exception handling
Exception handlingException handling
Exception handling
 
Access Protection
Access ProtectionAccess Protection
Access Protection
 
Java exception
Java exception Java exception
Java exception
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error Handling
 
Improve business process with microservice integration
Improve business process with microservice integration �Improve business process with microservice integration �
Improve business process with microservice integration
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
 
Java keywords
Java keywordsJava keywords
Java keywords
 

Semelhante a Exceptions in Java

UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptionsSujit Kumar
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptpromila09
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
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
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1Shinu Suresh
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptxsonalipatil225940
 

Semelhante a Exceptions in Java (20)

UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling
Exception handlingException handling
Exception handling
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
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
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Exception
ExceptionException
Exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 

Último

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

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

Notas do Editor

  1. NPEDisk has been removedURL does not exist. Socket exception
  2. 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).
  3. 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.
  4. 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).
  5. Creating your own exception class
  6. 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!”); }}
  7. 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.
  8. 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.
  9. Do not use exceptions to manage flow of control: exit a loop with a status variable rather than raising an exception.