Catching and Handling Errors

Sometimes it isn't easy (or possible) to check for all possible errors before executing a line of code.

Instead of calling these errors, there is a trend to call the exceptions (.net does this). After all, is "trying to write to a write protected floppy" an error or simply a system state that you may want to give the user a chance to modify?

Operating systems actually perform many functions for your programs (reading and writing files for example). When there is a failure, the operating system builds an object that describes the problem and raises an exception that is passed to your program. Then you have the option of

Visual Basic | Delphi | C++ Builder | Java | Windows API


Visual Basic 6.0

On Error GoTo lable1 ' This is the normal way to define and enable
                     ' an error handler

On Error GoTo 0      ' Disables the error handling

On Error Resume Next ' Ignore future errors and continue with the next line


Exit_Point:
  Exit Sub     ' This is needed to make sure the error handler
               ' is not run when there are no errors.
               ' Use "Exit Sub", "Exit Function", or
               ' "Exit Property" as appropriate

Lable1:  'The error handler starts here

  Resume       ' Continue with the statement that caused the error
  Resume Next  ' Continue with the statement after the one that failed
  Resume lable ' Continue with the specified statement

  Resume Exit_Point


   ' Err is the built-in error object
if Err = someNumber then    ' Check fo a specific error
Err.Clear                   ' Clear the error
Err.Raise 4                 ' Force/simulate error 4


Delphi 5.0


try
...
except
  on EDatabaseError do
  on ... do 
end;

try
 ...  // process file F
finally
  CloseFile(F);
  on ... do 
end;

You can (should) test for exceptions in the finally block.


C++ Builder


Java


.net

More details here


Windows API


Author: Robert Clemenzi - clemenzi@cpcug.org
URL: http:// cpcug.org / user / clemenzi / technical / Languages / CatchingErrors.htm