Exceptions are a powerful mechanism for centralized processing of errors and exceptional situations. This mechanism replaces the procedure-oriented method of error handling in which each function returns a code indicating an error or a successful execution.
2. Why??
An Error is any unexpected result obtained from a program during execution.
Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal
program termination.
Errors should be handled by the programmer, to prevent them from reaching the user.
When a program runs into a runtime error, the program terminates abnormally.
How can you handle the runtime error so that the program can continue to run or terminate
gracefully?
3. Errors and Error Handling
Some typical causes of errors:
Memory errors (i.e. memory incorrectly allocated, memory leaks,
“null pointer”)
File system errors (i.e. disk is full, disk has been removed)
Network errors (i.e. network is down, URL does not exist)
Calculation errors (i.e. divide by 0)
4. • Unexpected conditions
• Disrupt normal flow of program
• With exception handling, we can develop more robust programs
Exceptions
5. Exceptions
Exceptions are thrown
And can be caught.
How do you handle exceptions?
Exception handling is accomplished through
the “try – catch” mechanism, or by a “throws”
clause in the method declaration.
For any code that throws a checked
exception, you can decide to handle the
exception yourself, or pass the exception “up
the chain” (to a parent class).
6. Where do exceptions come from?
• JVM
OR
• Java Programs – can throw an exception
What are they?
An exception is a representation of an error condition or a situation that is not
the expected result of a method.
Exceptions are built into the Java language and are available to all program
code.
Exceptions isolate the code that deals with the error condition from regular
program logic.
11. Types of Exceptions
• Errors - serious and fatal problems
• Exceptions - can be thrown by any program, user can extend
• RuntimException - caused by illegal operations, thrown by JVM
(unchecked)
12. Checked Exceptions vs.
Unchecked Exceptions
RuntimeException, Error and their subclasses are known as unchecked
exceptions.
All other exceptions are known as checked exceptions - the compiler
forces the programmer to check and deal with the exceptions.
13. Checked or Unchecked Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Unchecked
exception.
14. Declaring, Throwing, and Catching
Exceptions
method1() {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
}
method2() throws Exception {
if (an error occurs) {
throw new Exception();
}
}
catch exception throwexception
declare exception
16. Declaring Exceptions
Every method must state the types of checked exceptions it might
throw. This is known as declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
17. Throwing Exceptions
When the program detects an error, the program can create an
instance of an appropriate exception type and throw it. This is known
as throwing an exception. Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
18. Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
19. Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
21. Catch or Declare Checked Exceptions
If a method declares a checked exception, you must invoke it in a try-catch block or declare
to throw the exception in the calling method.
In this example, method p1 invokes method p2 and p2 may throw a checked exception
(e.g., IOException)
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
(a) (b)
void p1() throws IOException {
p2();
}
23. Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Suppose no
exceptions in the
statements
24. Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block is
always executed
25. Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next Statement;
Next statement;
Next statement in the
method is executed
28. Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Execute the final block
29. Cautions When Using Exceptions
• Exception handling separates error-handling code from normal
programming tasks, thus making programs easier to read and to
modify.
• Exception handling usually requires more time and resources because
it requires instantiating a new exception object, rolling back the call
stack, and propagating the errors to the calling methods.
30. When to Throw Exceptions
• An exception occurs in a method.
• If you want the exception to be processed by its caller, you should
create an exception object and throw it.
• If you can handle the exception in the method where it occurs, there
is no need to throw it.
31. When to Use Exceptions
When should you use the try-catch block in the code? You should use it
to deal with unexpected error conditions. Do not use it to deal with
simple, expected situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
32. When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
33. Creating Custom Exception Classes
Use the exception classes in the API whenever possible.
Create custom exception classes if the predefined classes are not sufficient.
Declare custom exception classes by extending Exception or a subclass of
Exception.
34. Exceptions and Inheritance
How do you think exceptions affect overridden methods?
• if a method overrides a base class method, the new method cannot
throw a more general error, but can throw more specific.
• if the base class method throws no errors, the subclass method can't
either.