SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
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
 
Exception handling
Exception handlingException handling
Exception handling
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java IO
Java IOJava IO
Java IO
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Java threads
Java threadsJava threads
Java threads
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 

Andere mochten auch

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
 
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
 

Andere mochten auch (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
 
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
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 

Ähnlich wie 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
 
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
 

Ähnlich wie 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
 
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
 
Exception
ExceptionException
Exception
 

Kürzlich hochgeladen

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Kürzlich hochgeladen (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

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

Hinweis der Redaktion

  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.