Friday, November 19, 2010

Exception Handling Basics

Basics:

  • Events are abnormal activities that occur during runtime.
  • Errors are rather cataclysmic; there is no recovery or handling.
  • Exceptions are the unwanted problems in a program that don’t cause irrecoverable damage. Exceptions are, in effect, just errors that can be handled by guessing their occurrence in a particular section of code. They are of two types, Checked or Unchecked.
  • Runtime Environment is aware of most errors, called “Unchecked” Exceptions. E.g. Division by zero, typecasting between incompatible types, etc. Handling of these unchecked exceptions is not required, i.e. they don’t have to be “caught” or “declared thrown”.
  • On the other hand, “Checked” Exceptions must be caught and thrown explicitly. But in terms of functionality both are the same and no extra feature exists in either class of exceptions.
  • Handling is the practice of transferring control to special functions called handlers. Code is inspected in a “try” block, exception cases are detected and caught by “catch” blocks that work to handle and neutralize the problem imposed by the exception.

Important concepts:
(mainly C++)
1. The “try” block
Any statement or group of statements capable of generating an exception should be located in a try block. Exception objects are thrown in Java. In C++, a parameter is thrown whose type is matched to a catch block.

2. The “throw” keyword
This keyword is used to literally throw a value (C++) or object (Java) that is directly sent to catch blocks for evaluation. For example, in C++ one may write
throw 1;
Now a call will be made to a catch block that has the following prototype:
            catch(int arg) {;}

3. The “catch” block
The catch block catches the exception object(Java) or data type(C++). In C++, the type of the thrown parameter is matched to the prototype of the catch block. The match found is used to handle the thrown exception. Catch blocks contain error messages or substitute code that can help avoid the exceptional case.
A single try block can have multiple catch blocks but at least one catch is necessary that can handle all possible exceptions thrown from its parent try.
A default catch block that can accommodate all types is given below. It is used for default handling code.
            catch(…) {;}
“…” is an ellipsis that indicates no type specification.

No comments:

Post a Comment