Exception Handling
By Waqas 1
What is Exception? Error vs. Exception
Creating Custom Exceptions Throwing Custom Exceptions
Exception Message
Java Exceptions Hierarchy Exception Handling try block catch block finally block throw statement throws statement
Printing Exception Details
Exceptions and Overriding Methods Assertions in Java
Debugging in Java Code
Creating Debug Class
Controlling Application Debugging
By Waqas
Exception
By Waqas
Exception
An Exception is an event that occurs during the execution of the program and disturb the normal flow of instructions.
An exception is thrown by the program or the runtime environment, and can be caught or handled. An Error is similar to an exception but it represents a serious or un-recoverable situation, and should not be caught, rather letting the program terminate.
By Waqas
we write code to handle exceptions & continue program execution. Java has a predefined set of exceptions that may occur during the execution of the program. The super class of all errors and exception is Throwable which has two sub classes Error and Exception
By Waqas
Object
Throwable
Error
Exception
IOException
VirtualMachineError
Runtime Exception
By Waqas
Exception Message
When an exception is not handled by the program, the program terminates and produce a message that describes the type of exception occurred and where in the program it is occured.
Exception Handling
Exception handling allows a program to catch exceptions, handle them, and then continue program execution.
By Waqas 7
try Block
The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block.
try { statements }
By Waqas 8
A try statement must be accompanied by at least one catch block or one finally block.
If an exception occurs within the try statement, that exception is handled by the appropriate exception handler associated with this try statement.
By Waqas 9
catch Block
We associate exception handlers with a try statement by providing one or more catch blocks directly after the try block.
There can be no intervening code between the end of the try statement and the beginning of the first catch statement.
By Waqas
10
Example:
try { statements; statements; } catch(ArithmeticException e) { [Link](Error); }
By Waqas
11
Try with multiple Catch Blocks
try { statements; statements; } catch(ArithmeticException e) { } catch(ArrayIndexOutofBoundsException e) { }
By Waqas 12
finally Block
The finally statement defines a block of code that always executes, regardless of whether or not an exception occurred or caught. Finally block is often used to clean up resources or close the connection whether an exception occurs or not.
By Waqas 13
Try-Catch-Finally:
try { statements; statements; } catch(ArithmeticException e) { } catch(ArrayIndexOutofBoundsException e) { } finally { }
By Waqas 14
throw Statement
Throw statement is used to throw exceptions from java code. We can also create our own exceptions and throw them as needed using the throw statement. We can throw only the objects which are instance of any subclass of Throwable class. throw exceptionObject;
By Waqas
15
Throwing Exception
try { [Link](6/0); } catch(ArithmeticException e) { throw e; }
By Waqas
16
Throwing Exception
int a = 6; int b = 0;
if(b == 0) {
ArithmeticException e = new ArithmeticException(Error);
throw e; } else { [Link](a/b); }
By Waqas 17
Exceptions Wrapping
try { [Link](6/0); } catch(ArithmeticException e) { Exception ex = new Exception(e); throw ex; }
We are Wrapping Exception e into another Exception and then throwing it.
By Waqas 18
throws Statement
Any exception that is thrown out of a method must be specified by a throws clause. If a method is capable of causing an exception that it does not handle, it must specify this behavior so that the callers of the method can guard themselves against the exception. This is done by including throws clause in the methods declaration.
By Waqas
19
A throws clause lists the types of exceptions that a method might throw. All other exceptions, that a method can throw must be declared in the throws clause; otherwise a compile time error will result.
If method might throw more than one exception than all the exceptions are declared with comma separator.
By Waqas
20
public void print(int a, int b) throws ArithmeticException, NullPointerException {
By Waqas
21
Creating Custom Exceptions
We can also create custom exceptions in java. To create our own exception we extend either java Exception or RuntimeException class.
public class InvalidUserException Exception { public class InvalidUserException } RuntimeException { }
By Waqas
extends
extends
22
Throwing Custom Exceptions
We can throw custom exceptions in similar way as we throw java built in exceptions.
String name = james; if([Link](james)) { [Link](Welcome James); } else { InvalidUserException e; e = new InvalidUserException(Invalid User); By Waqas
23
Printing Exception Details
We can print user friendly error messages in by using following options:
try { [Link](6/0); } catch(ArithmeticException ex) { [Link](Invalid Input); [Link]([Link]()); [Link](Error: + [Link]()); } By Waqas
24
Printing Exception Details
We can print developer friendly messages with following options:
try { [Link](6/0); } catch(ArithmeticException ex) { [Link](ex); [Link]([Link]()); [Link](); }
By Waqas 25
Printing Full Exception Information
Java provides StackTraceElement class to get more information about the exception such as following: File Name Class Name Method Name Line Number
By Waqas
26
Printing Full Exception Information
try { [Link](6/0); } catch(ArithmeticException ex) { StackTraceElements errors[] = [Link]();
for(int i=0 ; i<[Link] ; i++) {
[Link](errors[i].getFileName()); [Link](errors[i].getClassName()); [Link](errors[i].getMethodName()); [Link](errors[i].getLineNumber());
By Waqas
27
Exceptions and Overriding Methods
Option 1: Child class method does not have to throw exception
class Shape { public void draw() throws RuntimeException { } }
class Circle extends Shape { public void draw() {
By Waqas 28
Exceptions and Overriding Methods
Option 2: Child class method can throw sub class of RuntimeException
class Shape { public void draw() throws RuntimeException { } }
class Circle extends Shape { public void draw() throws ArithmeticException By Waqas {
29
Exceptions and Overriding Methods
Option 3: Child class method can not throw parent of Exception
class Shape { public void draw() throws RuntimeException { } }
class Circle extends Shape { public void draw() throws Exception // ERROR {
By Waqas 30
Assertions in Java
Assertion refer to the verification of the condition that is expected to be true during the execution of the program.
Assertion facility can be enabled and disabled during the compilation or runtime.
Java implement assertion with a new keyword assert which is added in Java 1.4.
By Waqas 31
Assertions in Java
assert condition; or assert condition : [expression];
The condition must evaluate to true The expression is used to send error messages If assertions are enabled then condition will be evaluated. If condition is true java will not take any action If condition is false java will throw AssertionError
By Waqas
32
Assertions in Java
public class AssertionTest { public static void main(String args[]) { int a = 4; int b = 0; assert (b>0): Invalid Value: 0; [Link](a/b);
} Enabling Compiler Option: }
Enabling Interpreter Option: Disabling Interpreter Option:
-source 1.4 -ea -disableassertions
By Waqas 33
Note:
Do not use assertions to check the arguments passed to a method.
The expression in an assert statement must not product any side effects such as modifying the variable values.
By Waqas
34
Waqas Anwar
Sun Certified Java Programmer (SCJP) Sun Certified Web Component Developer for J2EE (SCWCD)
Microsoft Certified Professional ([Link]) Microsoft Certified Professional (C# .NET) Microsoft Certified Professional ([Link]) Microsoft Certified Professional (XML Web Services .NET) Microsoft Certified Application Developer (MCAD .NET)
[Link]
By Waqas 35
By Waqas
36