exceptions Flashcards
run-time errors
> Illegal/impossible operations to execute
Detected during program execution
But not detectable at compile time
Treated asexceptionsin Java
(examples: division by zero, using null reference, illegal format conversion)
what to do when an error occurs…
alternatives
> Ignore error
Print error message and terminate
Have the method handle the error in the code where the problem lies as best as you can
Have the method pass it off to someone else to handle
Usually an error code is returned to whoever called the method
> Modern language approach:Exception!
(note: in language like C, a “core dump” takes place)
how to indicate when a program generates an exception
“a program throws an exception”
In Java an exception is represented by an object
what to do when an exception occurs…
do nothing:
>Usually your program will be terminated by the JVM
>Stack trace is printed showing where exception was generated (Red and blue in Eclipse window)
do something:
>In some applications aborting the program is not an option (Email processor, web/database server)
> We can “handle” the exception by “catching the exception” and defining code to be executed
try
catch
Use try { } to enclose code that can potentially throw an exception
Use catch(EXCEPTIONTYPE e) { } to “catch” the exception and define the code to execute when the exception occurs
why is try catch somewhat similar to if else
> when an exception occurs control “jumps” to the catch clause and code after the point where the exception occurred is not executed
If the exception is not thrown the code of the catch clause is ignored
exception object
When an exception is thrown, a new exception object is created, which encodes information about the nature of the exception
Exception(String message)
Constructor taking an explanation as an argument
String getMessage()
Returns a message describing the exception
void printStackTrace()
Prints the contents of the Java call stack at the time of the exception
ArithmeticException
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 an object of type X in an array of type Y
EmptyStackException
attempt to pop an empty Stack (java.util)