Exceptions and Debugging - PowerPoint PPT Presentation

1 / 23
About This Presentation
Title:

Exceptions and Debugging

Description:

This is one of the only causes where the finally clause doesn't run. You can even use finally with no catch clause, again, for cleanup. ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 24
Provided by: chrisf2
Category:

less

Transcript and Presenter's Notes

Title: Exceptions and Debugging


1
Exceptions and Debugging
  • All Programs will encounter errors when they run
  • Files that supposed to exist sometimes dont (how
    many times has windows told you it cant find
    whatever.dll), Network connections go down
    unexpectedly, users enter data incorrectly,
    printers run out of paper in the middle of a job,
    etc.
  • Dealing with these are a pain. At the very
    least, the program should notify the user and
    exit gracefully.

2
Exception Handling
  • For situations where it is possible to crash to
    program, Java provides a form of error-trapping,
    called Exception Handling.
  • Exceptions can be thrown for different things
    Things that are may not be under your control
    (i.e., FileNotFound Exception for a missing file)
  • and things that are under your control
    (NullPointerExceptions, ArrayIndexOutOfBoundsExcep
    tion)

3
Exception Handling
  • In Java, every Exception is an instance of a
    class derived from Throwable.

4
Exception Handling
  • All Exceptions descend from Throwable, but the
    hierarchy immediately splits into two branches,
    Error and Exception.
  • The Error hierarchy describes internal errors and
    resource exhaustion inside the JVM itself. These
    are rare, and there really isnt much you can do
    about them besides notify the user and exit
    gracefully.
  • The Exception hierarchy is what we concentrate on
    when we deal with Exceptions

5
The Exception Hierarchy
  • Exception then basically splits into 2
    hierarchies itself Those that extend
    RuntimeException and those that do not.
  • RuntimeExceptions are things like bad casts,
    out-of-bounds array access and null pointer
    access.
  • Things that do not inherit from Runtime are
    things like trying to open a malformed URL and
    reading past the end of file.
  • Rule of Thumb If a RuntimeException occurs, it
    was your fault.

6
Throwing Exceptions
  • In C-style functions, if something bad
    happened, your would usually return some sentinal
    value to indicated an error occurred. This is
    flaky.
  • In Java, we can advertise and throw an Exception
    when that happens
  • public Image loadImage(String str)
  • throws EOFException, MalformedURLException
  • .
  • We only advertise Exceptions that do not inherit
    from RuntimeException. You would not advertise
    an IndexArrayOutOfBoundsException write code
    that doesnt overstep Array Bounds.

7
Throwing Exceptions
  • When an Exception occurs, you either deal with
    it, or pass it up to something that can deal with
    it better (or both).
  • With something like BufferedReader readLine()
    method, it makes sense to alert whoever called
    readLine() that it failed, and have them deal
    with it appropriately.
  • Sometimes an Exception can be handled (say, in
    some method, we attempt to read in a String from
    a network stream, but something goes wrong, but
    we can use a perfectly acceptable default value).
    We can handle this with a try/catch clause.

8
Passing an Exception Up
  • Say were writing a wrapper function for a
    BufferedReader readLine() method.
  • String readData(BufferReader in)
  • throws IOException
  • return in.readLine() //in.readLine
    can throw an Exception
  • If in.readLine happens to throw an IOException,
    well pass it up to whoever called the readData()
    method to deal with it.
  • So when something declares that it can throw it
    an exception, it basically makes the promise that
    it will return either the return data (a String,
    in this case) OR one of the declared exceptions.

9
Passing an Exception Up
  • So what happens if no one ever catches or deals
    with the Exception that is thrown?
  • The JVM will catch it, and your program will exit
    with a stacktrace
  • Make sure any possible exceptions that get thrown
    are dealt with somewhere.

10
try/catch blocks
  • Once an exception is thrown, we need to catch it
    somewhere in our code that knows how to deal with
    the situation that caused the exception and
    handle it properly.
  • A Simple try/catch blocks looks like a big if/if
    else statement, and behaves similarly
  • try
  • //code that can generate exception
  • catch (ExceptionType exp)
  • // code to deal with error

11
try/catch blocks
  • Some code can throw multiple types of exceptions
  • You can catch them all by catch the superclass
  • try
  • //buggy code here
  • catch (Exception exp) //This will capture
    all exceptions
  • //deal with it here
  • This is not the preferred method. You should
    explicitly list the types, and use the superclass
    afterwards as a catch-all, if necessary
  • try //buggy code here
  • catch (MalformedURLException e1)
  • catch (UnknownHostException e2)
  • catch (IOException e3)
  • catch (Exception exp) // if those all
    missed

12
try/catch blocks
  • In a chain of multiple catch statements, the
    first one that meet the condition is the only one
    that runs (like an if/else if)

13
Throwing Exceptions
  • In addition to Exceptions being thrown when
    something bad happens, you can throw them
    yourself with the throw command.
  • You could do this, for instance, to do cleanup
    before sending the exception up to the caller
  • Graphics g image.getGraphics()
  • try
  • //buggy code here
  • catch (MalformedURLException e)
  • g.dispose()
  • throw e

14
Throwing Exceptions
  • You can also just throw one as you see necessary
  • File configFilenew File(stuff.cfg)
  • if (!configFile.exists()) // if the config file
    doesnt exist
  • String errmsgConfig file does not exist
  • throw new IOException(errmsg)

15
The finally clause
  • When your code throws an exception, it stops
    processing the remaining code in your method.
    This can be a problem if there are resources you
    need to clean up.
  • You can catch and rethrow the Exception as shown
    in the previous example, but this can get
    repetitive, especially if youre testing for
    multiple kinds of Exceptions.
  • Java provides a method, called finally(), which
    runs after the try/catch clause REGARDLESS of
    whether or not an Exception was thrown.

16
The finally clause
  • InputStream in
  • try
  • //code that might throw exceptions
  • catch (IOException exp)
  • //show error dialog
  • finally
  • in.close() //clean up

17
The finally clause
  • Look at the following code. What gets printed?
  • try
  • throw new IOException("crash me,
    baby")
  • catch (IOException ioexp)
  • throw new NullPointerException("why
    me?")
  • finally
  • System.out.println("Do I print?")

18
The finally clause
  • Yes, the finally block in the previous slide
    does run. What about this?
  • try
  • throw new IOException("crash me,
    baby")
  • catch (IOException ioexp)
  • System.exit(0)
  • finally
  • System.out.println("Do I print?")

19
The finally clause
  • Now, it doesnt print. System.exit() kills all
    threads of execution. This is one of the only
    causes where the finally clause doesnt run. You
    can even use finally with no catch clause, again,
    for cleanup.
  • File dumpfilenew File(C\error.log)
  • try
  • //something that can throw exceptions
    here
  • finally
  • dumpfile.close()

20
Variable scoping in try/catch clauses
  • Variables declared inside try/catch clauses go
    out of scope was soon as that try/catch clause
    ends.
  • try
  • int a0
  • System.out.println(a) //This wont compile

21
Variable scoping in try/catch
  • The solution to this is simple, just declare the
    variable before the try/catch clauses if you want
    them to persist. Changes inside try/catch are
    NOT discarded.
  • int a5
  • try
  • a3
  • finally
  • System.out.println(a)
  • System.out.println(a) // 3 prints twice

22
Creating your own Exceptions
  • Sometimes the predefined Exception classes dont
    describe what happens correctly, and we might
    want to create our own type of exception
  • We simply extend one of the predefined Exception
    classes
  • class ConfigFileUnavailableException extends
    IOException
  • public ConfigFileUnavailableException()
  • public ConfigFileUnavailableException(String
    gripe)
  • super(gripe)
  • We can now throw this ourselves if we cant open
    our config file. Its more descriptive.

23
Other notes
  • If we want to find out what happened from an
    exception, we can call the toString() method on
    it.
  • catch (Exception exp)
  • System.out.println(exp.toString())
  • Exception handling is not supposed to replace
    simple tests. Exception handling is a lot slower
    and bulkier than simple tests. Dont do things
    like
  • try
  • s.pop() //pop something from a stack
  • catch (EmptyStackException e)
  • //do something here
  • When you could do this instead
  • if (!s.empty())
  • s.pop()
Write a Comment
User Comments (0)
About PowerShow.com