An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
It happens when an error occurs the method creates an exception object and hands it off to the runtime system.
The exception object contains information about the exception, including its type and the state of the program when the error occurred.
It happens when the exception object bubbles up through the call stack until an appropriate exception handler is found. The handler catches the exception.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception.
Table 6.1. Advantage 1
errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; ... } | readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } |
Table 6.2. Advantage 2
method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } | method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } |
catch (ArrayException e) { . . . } catch (Exception e) { . . . }
Copyright © 1998-2009 Dilvan Moreira