0% found this document useful (0 votes)
50 views21 pages

Exception Handling: Object Oriented Programming Ii

Exception handling separates error-handling code from normal processing code. It allows errors to be trapped and an appropriate message displayed to inform the user. There are two types of exceptions - checked exceptions that a program must handle to compile, and unchecked exceptions that do not require handling. Finally blocks ensure code is executed even if an exception occurs. Exception handling should be used to deal with unexpected errors, not for simple expected situations.

Uploaded by

EBONY Lord
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views21 pages

Exception Handling: Object Oriented Programming Ii

Exception handling separates error-handling code from normal processing code. It allows errors to be trapped and an appropriate message displayed to inform the user. There are two types of exceptions - checked exceptions that a program must handle to compile, and unchecked exceptions that do not require handling. Finally blocks ensure code is executed even if an exception occurs. Exception handling should be used to deal with unexpected errors, not for simple expected situations.

Uploaded by

EBONY Lord
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

EXCEPTION HANDLING

OBJECT ORIENTED PROGRAMMING II


◼ Traditional error handling
◼ Exception Handling
◼ Exception Handling Terminology
◼ Checked vs. Unchecked Exceptions
◼ Unhandled Exceptions
◼ Quirks and Problems with Exception Handling
◼ Examples of implementation
PROBLEMS WITH TRADITIONAL ERROR HANDLING

Some of the challenges faced with traditional error handling include:


◼ Normal code becomes cluttered with error handling code
◼ Programmer has to check the value returned by a method to see if an error occurred
◼ Error code returned has to be same data type as valid value returned
◼ Difficult to return error code in some cases e.g. a method that returns valid values true or false – there is no
other value to use for errors
EXCEPTION HANDLING

◼ 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

Many things can go wrong in a computer program:


◼ Errors can occur at compile time
◼ Errors can occur at run time
COMPILE TIME ERRORS

◼ These are errors that surface when a program is being compiled


◼ These prevent the program from being compiled successfully
◼ For example, syntax errors in the code. The following code will not compile in C++ or Java
RUN TIME ERRORS

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.

void method() throws IOException


{

}
FINALLY BLOCK

◼ The identifies a block of statements


that need to be executed regardless of
whether or not an exception occurs
within a try block
◼ For instance, a file or database may
have been opened or memory
allocated, then the exception occurs
and is handled before the code to
close the file/database or release the
memory was executed.
◼ The finally block is optional if there is a
catch block
WHEN TO USE EXCEPTION HANDLING

◼ 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

◼ Exception handling can lead to surprisingly irregular execution of code


◼ Exception handling can hide underlying errors by trapping the exceptions thrown but not sufficiency distilling
or handling the error that caused the exception
◼ Encourages lazy programmers
◼ Exception handling can cause resource leaks a resource is acquired and used by a method but an exception
occurs before the resource is released

You might also like