oops - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

oops

Description:

oops.ppt. 4. that's what's supposed to happen, but does it? ... oops.ppt. 6. how the runtime tries to help ... oops.ppt. 13. compile-time checks for error handling ... – PowerPoint PPT presentation

Number of Views:292
Avg rating:3.0/5.0
Slides: 29
Provided by: patpa
Category:
Tags: oops

less

Transcript and Presenter's Notes

Title: oops


1
oops

2
Javas Just in Time (JIT) compiler
at compile time
.class
.java
JIT compilation occurs the first time a method is
called, and only if its called
(cached in memory)
3
the way I write Java programs
  • first, I write a Java program
  • the Java compiler runs
  • it takes my .java files (plain text) as input
  • it creates .class files for me as output
  • each .class file contains Java bytecode
  • (some time passes)
  • later, I (or someone) runs my Java program
  • a Java Virtual Machine (JVM) runs
  • also called the Java Runtime Environment (JRE)
  • it reads the bytecode from my .class files
  • it then performs the actions specified by the
    bytecode

4
thats whats supposed to happen, but does it?
  • unintended conditions can occur at runtime, such
    as
  • missing file
  • server down
  • network down
  • such problems have two possible outcomes
  • my program hangs, or stops, and maybe prints an
    ugly message
  • my program informs the user what happened and
    then either tries to recover, or deliberately
    stops
  • Java is designed to encourage a good outcome
  • the compiler tries to force me to prepare for
    some problems
  • the runtime has mechanisms to help me handle
    problems
  • but, I have to do my part

5
life preservers in Java
  • objects created by the runtime upon problem
    occurence
  • Exception
  • and more than 200 of its subclasses
  • I can bunch my code into blocks with these
    keywords
  • try
  • catch
  • finally
  • I can pass the buck to my caller with these 2
    keywords
  • throws Exception
  • throw ex
  • where ex is a reference to an Exception

6
how the runtime tries to help
  • if while running, a program does something
    illegal, such as attempting to index outside the
    bounds of an array, the runtime steps in
  • it transfers control from the point where the
    exception occurred to a point that can be
    specified by the programmer
  • an exception is said to be thrown from the point
    where it occurred and is said to be caught at the
    point to which control is transferred
  • programmers can also throw exceptions explicitly,
    using throw statements

7
how does the runtime help me?
  • if the runtime detects that something impossible
    is about to happen
  • it abruptly ceases the current method
  • it creates an Exception object, and makes a
    reference to the Exception object available to my
    program
  • but, I have to have specified, in advance, how to
    use the Exception object

8
my mother had this saying that I hated
9
OK, what do I have to do?
  • but (theres always a but)
  • how do I know which code might fail?
  • lets say I diligently read the API before
    calling any method of a library class
  • about as likely as that pigs will fly
  • the compiler refuses to compile my code until I
    place it in a try ... catch ... block
  • a what?
  • heres the formula
  • put code that might give trouble in a try ...
    block
  • right below it, provide a catch ... block for
    failures

10
try-catch
  • String fileSpec c\numbers.txt
  • try
  • File f new File( fileSpec )
  • String s readFile(f)
  • another_risky_method()
  • catch (Exception e)
  • System.out.println(Oops.)
  • System.out.println(Im done)

11
a better try-catch
  • String fileSpec c\numbers.txt
  • try
  • File f new File( fileSpec )
  • String s readFile(f)
  • another_risky_method()
  • catch (FileNotFoundException e)
  • System.out.println(Could not find file
    fileSpec)
  • catch (Exception e)
  • System.out.println(Oops.)

12
heres some very risky code
  • public static void main(String args)
  • File f new File("c\\numbers.txt" )
  • String s readTextFile(f)
  • int newNums extract_the_numbers(s)
  • for (int i newNums) System.out.println(i)
  • System.out.println("main completed")
  • // end main

13
compile-time checks for error handling
  • a compiler for the Java programming language
    checks, at compile time, that a program contains
    handlers for checked exceptions
  • by analyzing which checked exceptions can result
    from execution of a method or constructor
  • for each checked exception which is a possible
    result, the throws clause for the method or
    constructor must mention the class of that
    exception (or one of its superclasses)
  • this compile-time checking for the presence of
    exception handlers is designed to reduce the
    number of exceptions which are not properly
    handled.

14
heres what I ended up needing to do
  • public static void main(String args)
  • String fileSpec "c\\numbers.txt"
  • File f new File( fileSpec )
  • String s null
  • try s readTextFile(f)
  • catch (IOException e)
    System.out.println( e.getMessage() )
  • int newNums extract_the_numbers(s)
  • if (newNums ! null)
  • for (int i newNums)
    System.out.println(i)
  • System.out.println("main completed")
  • // end main

15
finally block
  • finally always executes when the try block
    exits
  • ensures that something occurs even if an
    unexpected exception occurs
  • useful for more than just exception handling
  • avoids having cleanup code accidentally bypassed
    by a return, continue, or break
  • cleanup by a finally block is a good practice,
    even when no exceptions are anticipated
  • a call to System.exit(0) anywhere will stop
    everything immediately
  • in which case the finally clause might not
    execute after all

16
high-risk activities
  • try-catch-finally can save you from these (and
    the compiler insists that you watch for problems
    with these)
  • files
  • networks (and servers)
  • database access
  • using libraries (packages)
  • asking the operating system for stuff
  • your own watchfulness and testing can save you
    from these (unchecked exceptions which are
    subclasses of RuntimeExceptionno compiler
    enforcement)
  • arithmetic (divide by zero, integer overflow,
    etc.)
  • array indexing
  • casting

17
common RuntimeException subclasses in Java 5
  • code should be written in such a way as to avoid
    having these things happen
  • ArithmeticException
  • BufferOverflowException
  • BufferUnderflowException
  • ClassCastException
  • EmptyStackException
  • IllegalArgumentException
  • IndexOutOfBoundsException
  • NullPointerException
  • the compiler does not force you to check for
    these they are thus called unchecked exceptions

18
the Java compiler tries to save the day
  • the Java compiler will not compile source code
  • unless the code specifies an action for every
    checked Exception that could possibly occur
  • this encompasses about 80 of known failures
  • compile-time checking for Exception handling
    forces you to deal with about 80 of all kinds of
    things that can go wrong
  • the other 20 are unchecked because you ought
    not to be doing anything that would cause those
    problems (and if they occur, its your fault)

19
throws clause on method declarations
  • the Exceptions (or its subclasses) following a
    throws keyword are part of the contract between
    the implementor and user of a method (or
    constructor)
  • if you override a method, the subclass throws can
    only do what the superclass does

20
how the compiler uses the throws keyword
  • compiler analyzes which checked exceptions can
    result from execution of a method or constructor
  • for each checked exception which might result,
    the throws clause for the method (or constructor)
    must mention the Exception (or one of its
    superclasses)

21
the JDK includes lots of libraries
  • Java programs can call a huge body of pre-written
    code
  • these reusable components are called the Class
    Libraries
  • sometimes they are also called packages
  • they are also called the Java APIs
  • the libraries are designed to be used identically
    regardless of OS
  • the library Application Programming Interface
    (API) for a class tells us what Exception
    subclasses can be thrown by each method

22
The Exception hierarchy (Java 5)
Object
Throwable
Error
Exception
9
unchecked
checked
RuntimeException
8 other subclasses
69
ArithmeticException
37
98
23
Throwable
  • the superclass of all errors and exceptions in
    the Java language
  • only objects that are instances of this class (or
    one of its subclasses) are thrown by the Java
    Virtual Machine or can be thrown by the Java
    throw statement
  • only this class or one of its subclasses can be
    the argument type in a catch clause

24
Throwable objects
  • Instances of two subclasses, Error and Exception,
    are used to indicate that exceptional situations
    have occurred
  • these instances are freshly created in the
    context of the exceptional situation so as to
    include relevant information (such as stack trace
    data)
  • a throwable contains a snapshot of the execution
    stack of its thread at the time it was created
  • it can also contain a message string that gives
    more information about the error
  • it can contain a cause another throwable that
    caused this throwable to get thrown
  • cause was new in release 1.4-- also known as the
    chained exception facility, as the cause can,
    itself, have a cause, and so on, leading to a
    "chain" of exceptions, each caused by another

25
unchecked Exception
  • RuntimeException
  • the superclass of exceptions that can be thrown
    during the normal operation of the Java Virtual
    Machine
  • a method is not required to declare these in its
    throws clause (even if they can occur)
  • likewise, a caller is not required by the
    compiler to handle these well
  • they are not supposed to happen at all if the
    programming is careful

26
subsclasses of RunTimeException in Java 1.4.2
ImagingOpException IndexOutOfBoundsException Missi
ngResourceException NegativeArraySizeException NoS
uchElementException NullPointerException ProfileD
ataException ProviderException RasterFormatExcepti
on SecurityException SystemException UndeclaredTh
rowableException UnmodifiableSetException Unsuppor
tedOperationException
ArithmeticException ArrayStoreException BufferOver
flowException BufferUnderflowException CannotRedoE
xception CannotUndoException ClassCastException C
MMException ConcurrentModificationException DOMExc
eption EmptyStackException IllegalArgumentExcepti
on IllegalMonitorStateException IllegalPathStateEx
ception IllegalStateException
increased from 29 to 37 in Java version 5.0
27
the ultimate reference on Exceptions
  • from Java Language Specification, Second Edition
  • http//java.sun.com/docs/books/jls/second_edition/
    htmlexceptions.doc.html
  • Chapter 11, Exceptions

28
the end of this PowerPoint file
Hooray!
Write a Comment
User Comments (0)
About PowerShow.com