exceptions
Download
Skip this Video
Download Presentation
Exceptions

Loading in 2 Seconds...

play fullscreen
1 / 24

Exceptions - PowerPoint PPT Presentation


  • 133 Views
  • Uploaded on

Exceptions. Syntax, semantics, and pragmatics. Syntax, semantics, pragmatics. Syntax How it looks, i.e. how we have to program to satisfy the compiler. Semantics What it means / how it works Pragmatics How to use it in the proper way. Introduction.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Exceptions' - ferdinand-reilly


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
exceptions

Exceptions

Syntax, semantics, and pragmatics

Exceptions

syntax semantics pragmatics
Syntax, semantics, pragmatics
  • Syntax
    • How it looks, i.e. how we have to program to satisfy the compiler.
  • Semantics
    • What it means / how it works
  • Pragmatics
    • How to use it in the proper way.

Exceptions

introduction
Introduction
  • Exceptions are a part of the Java programming language
    • And other programming languages like C++, C#, etc.
  • Exception related keywords in Java
    • throw, throws, try … catch … finally

Exceptions

more syntax multi catch
More syntax: Multi catch
  • General try … catch
    • try { do something dangerous}
    • catch (SomeException ex) { handle the exception}
  • Multi catch
    • Java 7 feature

Catch (SomeExceptionType|SomeOtherExceptionType ex) { Handle exception}

    • Useful if you want the same handling for different exceptions

Exceptions

exception class hierarchy
Exception class hierarchy
  • The class hierarchy can get quite deep
    • java.lang.Object
      • java.lang.Throwable
        • java.lang.Exception
          • java.sql.SQLException
          • java.ql.SQLWarning
    • More detailed exceptions
      • More detailed information on the problem
      • More detailed handling of the problem

Exceptions

checked vs runtime exceptions
Checked vs. runtime exceptions
  • Checked exceptions
    • Extends Exception, directly or indirectly.
    • Must be caught or declared to be thrown
      • This is checked by the compiler
      • Called the “Catch or specify requirement”
        • http://download.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
    • Can usually be recovered from at runtime
  • Run-time exceptions
    • Extends RuntimeException, directly or indirectly
    • Can be caught or declared to be thrown
      • This is not checked by the compiler
    • Can usually not be recovered from at runtime

Exceptions

the class error
The class Error
  • By convention the class Error is reserved for use by the JVM to indicate problems in the JVM.
    • Don’t ever subclass Error
    • Don’t ever throw an Error
      • Unless you are programming a JVM, of course!

Exceptions

what happens when an exception is thrown
What happens when an exception is thrown?
  • When an exception is thrown the current block ({…}) is popped of the call stack
  • This popping continues until some block has a catch clause.
  • If no block has a catch clause we will eventually end in main, which is then popped
    • And the program stops.

Exceptions

sequence of catch blocks
Sequence of catch blocks
  • If a block has more than one catch block the first catch block, that matches the exception type, is executed.
  • General rule:
    • Special exception must be caught beforegeneral exceptions

Try { … }

catch (FileNotFoundException ex) { …}

catch (IOException ex) { …}

Exceptions

different kinds of exception handling
Different kinds of exception handling
  • Ignore
    • Usually a bad programming habit used by 1st semester students to make the compiler shut up!
  • Handle
    • Only handle the exception if you really can.
    • Just printing something to the screen is usually a bad idea, except if you are in the user interface layer.
  • Re-throw
    • If you don’t know how to deal with the exception re-throw it.
  • Partly handle + re-throw
    • Sometimes you want to partly handle the exception for example write to a log file, and then re-throw the exception.

Exceptions

finally
Finally
  • The finally block is executed whether or not an exception is thrown.
    • Leaving the method you always execute the finally block
  • Used to release resources
    • Example: Closing a connection to a network, database, or file
    • Coding idiom:

FileReader input = null;

try { … open input and use it … }

finally { if (input != null) { input.close(); } }

Example: java7exceptionfeatures

Exceptions

try with resource statement
Try with resource statement
  • Java 7 language feature
  • The coding idiom
    • Declare … try { open + use } finally {close }
    • Is now supported in the Java programming language
  • New syntax
    • Try (open + initialize) { use }
    • The resource must implement the java.lang.AutoCloseable interface
    • Finally is no longer necessary in this case
    • Example: java7exceptionfeatures
    • Further readings + examples
      • The Java Tutorial
        • http://download.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Exceptions

program your own exception
Program your own exception
  • Why?
    • Technical exceptions like IOException, SQLException, etc. should not be propagated to the model layer.
    • Instead you must define your own application specific exception like LibraryException
    • Example: eventLayersExceptions
  • How? That’s very easy!
    • Define a new class which extends the class Exception
    • You probably need to define 3 constructors.
    • Your exception class may have data + methods
      • But you probably never need it.
    • NetBeans can assist you.

Exceptions

item 57 use exceptions only for exceptional conditions
Item 57: Use exceptions only for exceptional conditions
  • Don’t loop over a collection until it throws an exception.
  • A well-designed API must not force the users to use exception for ordinary control flow

Exceptions

item 58 checked exceptions vs run time exceptions
Item 58: Checked exceptions vs. run-time exceptions
  • Use checked exceptions for recoverable conditions and run-time exceptions for programming errors
    • Use checked exception for conditions form which the call can reasonably be expected to recover.
    • Use run-time exceptions to indicate programming error
      • The caller (programmer) made an error
        • Most likely a violation the methods precondition
        • Examples: IndexOutOfBoundException, NullPointerException

Exceptions

item 59 avoid unnecessary use of checked exceptions
Item 59: Avoid unnecessary use of checked exceptions
  • If the caller cannot handle the exception, then throw a run-time exception.
  • Provide check methods
    • Example: StringTokenizer.hasMoreElements()

Exceptions

item 60 favor the use of standard exceptions
Item 60: Favor the use of standard exceptions
  • Don’t use a home-made exception if you can use a standard exception.
  • Specially with run-time exceptions.
  • Reusable standard run-time exceptions
    • IllegalArgumentException
    • IllegalStateException
    • NullPointerException
    • IndexOutOfBoundsException
    • UnsupporteOperationException

Exceptions

item 61 throw exceptions appropriate to the abstraction
Item 61: Throw exceptions appropriate to the abstraction
  • Higher layers should catch lower-level exceptions and throw exceptions appropriate for the higher level
  • Exception translation
    • Catch (LowLevelException ex) { throw new HighLevelException(message); }
  • Exception chaining
    • Catch (LowLevelException ex) { throw new HighLevelException(ex); }
    • The LowLevelException is “inside” the HighLevelException
    • New in Java 1.4: New constructor in class Throwable

Exceptions

item 62 document all exceptions thrown by each method
Item 62: Document all exceptions thrown by each method
  • For all your methods
    • Document (using the Javadoc @throws tag) all the exceptions the method might throw
    • Including unchecked exceptions.
  • NetBeans can assist you
    • Mainly with checked exceptions.
    • Don’t forget the run-time exceptions.

Exceptions

item 63 include failure capture information in detail message
Item 63: Include failure-capture information in detail message
  • The message in the exception is the only information the receiver gets.
  • The message in the exception should include all values that “contributed” to the exception
    • Example
      • throw new IllegalArgumentException(“….” + parameter)

Exceptions

item 64 strive for failure atomicity
Item 64: Strive for failure atomicity
  • A failed method should invocation should leave the object in the state that it was prior to invocation.
    • Easier to recover from exception.

Exceptions

item 65 don t ignore exceptions
Item 65: Don’t ignore exceptions
  • An empty catch block is highly suspicious
    • If you really mean it, then write a comment in the empty catch block.
    • In JUnit test you sometimes see an empty catch block
      • But even here you can improve

catch (SomeException ex) {

assertEquals(“….”, ex.getMessage();

}

Exceptions

references
References
  • Ken Arnold et al.: The Java Programming Language, 4th edition, Addison Wesley, 2006
    • Chapter 12: Exceptions and Assertions, page 279-303
  • Joshua Bloch: Effective Java, 2nd edition, Addison Wesley, 2008
    • Chapter 9: Exceptions, page 241-258

Exceptions

ad