Title: COMPE 438 JAVA PROGRAMMING
1COMPE 438JAVA PROGRAMMING
2Exceptions
- In Java error exception
- Programs can generate errors
- Arithmetic
- Divide by zero, overflows,
- Object / Array
- Using a null reference, illegal array index,
- File and I/O
- Nonexistent file, attempt to read past the end of
the file, (well see more about file I/O later in
course), - Application-specific
- Errors particular to application (e.g., attempt
to remove a nonexistent customer from a database)
3Exceptions
void readFile String fileName
c\a.txt openFile(fileName) findSize(fileName
) allocateMemory(fileName) readFileFromMemory(
fileName) closeFile(fileName)
4Exceptions
- unexpected conditions in programs
- approaches for dealing with error conditions
- Use conditional statements and return values
- Use Javas exception handling mechanism
- java exception handling facilitates recovery from
unexpected condition or failures - you can restore program stability (or exit
gracefully) - sources of exception
- Run-time environment, including java class
library - Java programs
5Exceptions(cont.)
6Exceptions(cont.)
- Unchecked Exceptions
- represent defects in the program (bugs) - often
invalid arguments passed to a non-private method.
(errors in your program's logic) - are subclasses of RuntimeException, and are
usually implemented using IllegalArgumentException
, NullPointerException, or IllegalStateException - a method is not obliged to establish a policy for
the unchecked exceptions thrown by its
implementation (and they almost always do not do
so)
7Exceptions(cont.)
- Checked Exceptions
- represent invalid conditions in areas outside the
immediate control of the program (invalid user
input, database problems, network outages, absent
files) - are subclasses of Exception
- a method is obliged to establish a policy for all
checked exceptions thrown by its implementation
(either pass the checked exception further up the
stack, or handle it somehow)
8Exceptions(cont.)
- Throwable is the superclass of all errors
- different categories of Throwable
- Error
- serious and fatal problems in programs
- thrown by JVM, not handled by regular programs
- Exception
- thrown by any program
- user-defined exceptions are subclasses of
Exception - RuntimeException
- subclass of Exception
- caused by illegal operations
- thrown by JVM
9Exceptions(cont.)
- Throwing Exceptions
- throw exception anywhere in a program
- use throw statement
throw Exception
10Exception Behaviour
- If program generates (throws) exception then
default behavior is - Java clobbers (aborts) program
- Stack trace is printed showing where exception
was generated
11Exception Behaviour
public static int findIndex(int ints, int
s) for (int ret 0 ret lt ints.length
ret) if (intsret s) return ret return
-1
Consider
int ints 0, 2, 1, 5
Evaluating findIndex(ints, 6) results in
Exception in thread "main" java.lang.ArrayIndexOut
OfBoundsException 4 at exceptionExamples.SearchEx
ample.findIndex(SearchExample.java13) at
exceptionExamples.SearchExample.main(SearchExample
.java27)
12Java Exception Terminology
- When an anomaly is detected during program
execution, the JVM throws an exception - There are built-in exception
- Users can also define their own (more later)
- To avoid crashing, a program can catch a thrown
exception - An exception generated by a piece of code can
only be caught if the program is alerted. - This process is called trying the piece of code
13Java Exception Terminology
- Every exception object has the following methods
- Exception(String message)
- Constructor taking an explanation as an argument
- String getMessage()
- Returns the embedded message of the exception
- void printStackTrace()
- Prints the Java call stack when the exception was
thrown
14Examples from Java library
- ArithmeticException Used e.g. for divide by zero
- NullPointerException attempt to access an object
with a null reference - IndexOutOfBoundsException array or string index
out of range - ArrayStoreException attempting to store wrong
type of object in array - EmptyStackException attempt to pop an empty
Stack (java.util) - IOException attempt to perform an illegal
input/output operation (java.io) - NumberFormatException attempt to convert an
invalid string into a number (e.g., when calling
Integer.parseInt( ) ) - RuntimeException general run-time error
(subsumes above) - Exception The most generic type of exception
15Handling Exceptions in Java
- Java uses try-catch blocks for exception
handling. Syntax
try catch (ltexntype1gt e2)
catch(ltexntype2gt e2) finally //
finally is optional
16Example
public static void main(String args) int
ints 0, 2, 1, 5 try System.out.print
("Searching for 6. ") System.out.println ("Index
is " findIndex(ints, 6)) catch
(IndexOutOfBoundsException e) System.out.println
("\nThere must be an array error.") System.out.p
rintln ("Message is " e.getMessage())
17Exception Propagation
- Java uses exception propagation to look for
exception handlers - When an exception occurs, Java pops back up
the call stack to each of the calling methods to
see whether the exception is being handled (by a
try-catch block). This is exception propagation. - The first method it finds that catches the
exception will have its catch block executed.
Execution resumes normally in the method after
this catch block - If we get all the way back to main and no method
catches this exception, Java catches it and
aborts your program
18Throwing Exceptions in Java
- To throw an exception, use throw command throw
e - e must evaluate to an exception object
- You can create exceptions just like other objects
- RuntimeException is a class
- Calling new this way invokes constructor for this
class - RuntimeException generalizes other kinds of
exceptions (e.g. ArithmeticException)
RuntimeException e new RuntimeException(Uh
oh)
19Example
public class EasyExample public static void
g(boolean b) System.out.println ("Entering g
...") if (b) throw new RuntimeException("Oh no,
you really messed up...") System.out.println
("Exiting g ...") public static void f(int i)
System.out.println ("Entering f ...") g(i
0) System.out.println ("Exiting f
...") public static void main(String args)
try f(1) catch (RuntimeException e)
System.out.print ("Runtime error. Message
") System.out.println (e.getMessage())
20Example
public class EasyExample public static void
g(boolean b) System.out.println ("Entering g
...") if (b) throw new RuntimeException("Oh no,
you really messed up...") System.out.println
("Exiting g ...") public static void f(int i)
System.out.println ("Entering f ...") g(i
0) System.out.println ("Exiting f
...") public static void main(String args)
try f(0) catch (RuntimeException e)
System.out.print ("Runtime error. Message
") System.out.println (e.getMessage()) System.
out.println ("Exiting g ...")
21Exceptions(cont.)
public FileReader(String fileName) throws
FileNotFoundException
class OpenFile public static void
main(String args) if (args.length
gt 0) try
// Open a file
FileReader f new
FileReader(args0)
System.out.println(args0
" opened")
f.close() catch (IOException x)
System.out.println(x)
22Exceptions(cont.)
class Inventory private int stockLevel
0 public boolean addToInventory (int
amount) final int MAX 100 int temp temp
stockLevel amount if (temp gt
MAX) System.out.print("Adding " amount "
item will cause stock ") System.out.printl
n("to become greater than " MAX "
units(overstock)") return false else stockLe
vel stockLevel amount return true //
End of method addToInventory
23Exceptions(cont.)
public void addToInventory (int amount) throws
InventoryOverMaxException int
temp temp stockLevel amount if (temp gt
MAX) throw new InventoryOverMaxException
("Adding " amount " item
will cause stock to become greater than "
MAX " units")
class InventoryOverMaxException extends
Exception public InventoryOverMaxException
() super () public InventoryOverMaxException
(String s) super (s)