Exception Handling: Object Oriented Programming Ii
Exception Handling: Object Oriented Programming Ii
◼ An exception is a signal generated when an abnormal event has occurred in a running program
◼ Used to manage situations which are outside the normal flow of program execution
◼ Separates error-handling code from normal processing code
◼ Exceptions alter the flow of execution in a program – from normal processing to executing an exception handler
◼ Exception handling allows errors to be trapped and an appropriate message displayed to the user informing that
an error has occurred
◼ Use exceptions to indicate or signal that an error has occurred
◼ Exceptions are separate from the return values of methods
◼ Exceptions can be logged so that the developer can use the log to debug the program at a later date
EXCEPTION HANDLING BENEFITS
◼ Separates error handing code from regular code, handling the exception in a catch handler
◼ If possible, allows program to run normally after exception has occurred
◼ If this is not possible, allows a graceful shutdown of the program instead of an abrupt termination
◼ Sufficiently handle unexpected occurrences
ERRORS IN COMPUTER PROGRAMS
These occur while the program is running. Run time errors can be:
◼ Synchronous
◼ Occur while the statements of the program are being executed, some of the errors listed may occur:
◼ Divide by zero
◼ Invalid array index (array out of bounds)
◼ Invalid number format (entering a string when a number was expected)
◼ Overflow and underflow
◼ Null pointer dereferencing
◼ Asynchronous
◼ These occur outside of your currently executing program
◼ Therefore occurring independent of your program, Examples:
◼ Mouse and keyboard errors
◼ Network message errors
◼ Disk Input/output errors
EXCEPTION HIERARCHY (JAVA)
ERRORS VS EXCEPTIONS
◼ System errors are thrown by JVM and represented in the Error class. The Error class describes internal system
errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to
terminate the program gracefully.
◼ Exception describes errors caused by your program and external circumstances. These errors can be caught
and handled by your program.
CHECKED VS UNCHECKED EXCEPTIONS
Unchecked Exceptions
◼ These are exceptions that a program is not required to handle – the program will compile successfully even if no exception handler is
present
Checked Exceptions
◼ These are exceptions that a program must handle. The program will not compile if no exception handler is present or if the
exception is not declared (so it can be propagated forward).
◼ RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked
exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.
◼ In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException
is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is
thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in
the program.
◼ Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not
mandate you to write code to catch unchecked exceptions.
EXCEPTION HANDLING – KEY TERMINOLOGY
Term Description
Exception An object, attribute, variable or value that is used to signal that a particular runtime
error has occurred
Throw/Raise an exception Generate an exception to indicate that an error has occurred during the running of a
program
Throw point The line of code from which an exception was generated
Catch handler A block of code written to handle a specific exception. There may be more than one
catch blocks
Exception handler The code involved in the try and catch blocks
Try Block A block of code which surrounds normal code and which may contain one or more
throw points
STACK UNWINDING
THROWING AN EXCEPTION
◼ In Java, there is already defined exception classes such as ArithmeticException, NullPointerException, etc.
◼ These exceptions are implicitly thrown by JVM
◼ The throw keyword may be used to explicitly throw an exception of a desired type
CREATING A NEW CLASS OF EXCEPTIONS
You can define your own exception classes by inheriting from the existing exception classes
EXCEPTION HANDLING EXAMPLE
…
int amt;
try
{
System.out.println("Now in CalculateRetailContainersNeeded()”);
amt = wcSize / rcSize;
}
catch(ArithmeticException e)
{
System.out.println(“Divisor Cannot be Zero”);
System.out.println(e.getMessage());
rcSize = 1;
}
catch(InputMismatchException e) {System.out.println(e.getMessage());}
catch(MyException e) {System.out.println(e.getMessage());}
catch(Exception e) {System.out.println(e.getMessage());}
THROWING/RAISING AN EXCEPTION
…
int amt;
try
{
System.out.println("Now in CalculateRetailContainersNeeded()”);
if(rcSize == 0)
throw new ArithmeticException();
amt = wcSize / rcSize;
}
catch(ArithmeticException e)
{
System.out.println(“Divisor Cannot be Zero”);
System.out.println(e.getMessage());
rcSize = 1;
}
catch(Exception e) {System.out.println(e.getMessage());}
EXCEPTION SPECIFIERS
◼ The throws keyword is used to declare on a method any possible exceptions that may the raised.
◼ This can help developers know that it is best that they provide exception handling code so that normal flow can
be restored.
◼ 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 {
if (refVar != null)
System.out.println(refVar.toString());
System.out.println(refVar.toString());
}
else
catch (NullPointerException ex) {
System.out.println("refVar is null"); System.out.println("refVar is null");
}
ISSUE WITH EXCEPTION HANDLING