Adv Oop Lect15

Embed Size (px)

Citation preview

  • 8/13/2019 Adv Oop Lect15

    1/6

    Osman Khalid, Lecturer, Computer Sciences Department, COMSATS Institute of Information Technology

    Lecture (23 Dec)

    Errors and Exceptions

    Exception Classes

    In C#, an exception is an object created (or thrown ) when a particular exceptionalerror condition occurs.

    Two important classes in the hierarchy are derived from System.Exception :

    System.SystemException

    This class is for exceptions that are usually thrown by the .NET runtime or that areconsidered to be of a generic nature and might be thrown by almost any application.

    For example, StackOverflowException will be thrown by the .NET runtime if it detectsthe stack is full.

    However, you might choose to throw ArgumentException or its subclasses in yourown code, if you detect that a method has been called with inappropriate arguments.

    Subclasses of System.SystemException include classes that represent both fatal andnonfatal errors.

    System.ApplicationException

    This class is important, because it is the intended base for any class of exceptiondefined by third parties.

    If you define any exceptions covering error conditions unique to your application, youshould derive these directly or indirectly from System. ApplicationException .

    Downloaded from: www.onspot.pk

  • 8/13/2019 Adv Oop Lect15

    2/6

    Osman Khalid, Lecturer, Computer Sciences Department, COMSATS Institute of Information Technology

    Other exception classes that might come in handy include the following:

    StackOverflowException

    This exception is thrown when the area of memory allocated to the stack is full.

    A stack overflow can occur if a method continuously calls itself recursively. This is generally a fatal error, because it prevents your application from doinganything apart from terminating (in which case it is unlikely that even the finally block willexecute). Trying to handle errors like this yourself is usually pointless; instead, you should getthe application to gracefully exit.

    EndOfStreamException

    The usual cause of an EndOfStreamException is an attempt to read past the end of afile. A stream represents a flow of data between data sources.

    OverflowException An OverflowException is what happens if you attempt to castan int containing a value of - 40 to a uint in a checked context.

    Downloaded from: www.onspot.pk

  • 8/13/2019 Adv Oop Lect15

    3/6

    Osman Khalid, Lecturer, Computer Sciences Department, COMSATS Institute of Information Technology

    Catching Exceptions

    try blocks encapsulate the code that forms part of the normal operation of yourprogram and that might encounter some serious error conditions.

    catch blocks encapsulate the code that deals with the various error conditions that

    your code might have encountered by working through any of the code in theaccompanying try block.This place could also be used for logging errors.

    finally blocks encapsulate the code that cleans up any resources or takes any otheraction that you will normally want done at the end of a try or catch block. It is important to understand that the finally block is executed whether or not anexception is thrown. Because the aim is that the finally block contains cleanup code that should always beexecuted, the compiler will flag an error if you place a return statement inside a finallyblock. For an example of using the finally block, you might close any connections that were

    opened in the try block. It is also important to understand that the finally block is completely optional. If you do not have a requirement for any cleanup code (such as disposing or closingany open objects), then there is no need for this block.

    So how do these blocks fit together to trap error conditions? Here is how:

    1. The execution flow first enters the try block.

    2. If no errors occur in the try block, execution proceeds normally through the block, and

    when the end of the try block is reached, the flow of execution jumps to the finally blockif one is present (Step 5). However, if an error does occur within the try block, executionjumps to a catch block (Step 3).

    3. The error condition is handled in the catch block.

    4. At the end of the catch block, execution automatically transfers to the finally block ifone is present.

    5. The finally block is executed (if present).

    The C# syntax used to bring all of this about looks roughly like this:

    try{// code for normal execution}catch{// error handling}

    Downloaded from: www.onspot.pk

  • 8/13/2019 Adv Oop Lect15

    4/6

    Osman Khalid, Lecturer, Computer Sciences Department, COMSATS Institute of Information Technology

    finally{// clean up}

    Actually, a few variations on this theme exist:

    You can omit the finally blockbecause it is optional.You can also supply as many catch blocksas you want to handle specific types of

    errors.However, the idea is not to get too carried away and have a huge number of catchblocks, because this can hurt the performance of your application.

    You can omit the catch blocksaltogether, in which case the syntax serves not toidentify exceptions, but as a way of guaranteeing that code in the finally block will beexecuted when execution leaves the try block. This is useful if the try block containsseveral exit points.

    Now your try block looks like this:

    try{// code for normal executionthrow new OverflowException();}// more processingcatch (OverflowException ex){// error handling for the overflow error condition

    }finally{// clean up}

    EXAMPLE

    The code for SimpleExceptions looks like this:

    Downloaded from: www.onspot.pk

  • 8/13/2019 Adv Oop Lect15

    5/6

    Osman Khalid, Lecturer, Computer Sciences Department, COMSATS Institute of Information Technology

    using System;namespace Wrox.ProCSharp.AdvancedCSharp{public class MainEntryPoint{

    public static void Main(){

    while (true){try{string userInput;Console.Write(Input a number between 0 and 5 +(or just hit return to exit) > );userInput = Console.ReadLine();if (userInput == ){break;

    }int index = Convert.ToInt32(userInput);

    if (index < 0 || index > 5){throw new IndexOutOfRangeException(You typed in + userInput);}Console.WriteLine(Your number was + index);}catch (IndexOutOfRangeException ex){Console.WriteLine(Exception: +

    Number should be between 0 and 5. {0}, ex.Message);}catch (Exception ex){Console.WriteLine(An exception was thrown. Message was: {0}, ex.Message);}catch{Console.WriteLine(Some other exception has occurred);}finally{

    Console.WriteLine(Thank you);}}}}}

    Downloaded from: www.onspot.pk

  • 8/13/2019 Adv Oop Lect15

    6/6

    Osman Khalid, Lecturer, Computer Sciences Department, COMSATS Institute of Information Technology

    The following output illustrates what happens with different inputs and demonstrates both theIndexOutOfRangeException and the FormatException being thrown:SimpleExceptions

    Input a number between 0 and 5 (or just hit return to exit) > 4Your number was 4Thank youInput a number between 0 and 5 (or just hit return to exit) > 0Your number was 0Thank youInput a number between 0 and 5 (or just hit return to exit) > 10Exception: Number should be between 0 and 5. You typed in 10Thank youInput a number between 0 and 5 (or just hit return to exit) > hello

    An exception was thrown. Message was: Input string was not in a correct format.Thank youInput a number between 0 and 5 (or just hit return to exit) >Thank you

    Why is this second catch block even here? Well, it is not only your code that iscovered by the try block. Inside the block, you actually make three separate calls tomethods in the System namespace ( Console.ReadLine() , Console.Write() , andConvert.ToInt32() ), and any of these methods might throw an exception.

    If you type in something that is not a number say a or hello theConvert.ToInt32() method will throw an exception of the class System.FormatExceptionto indicate that the string passed into ToInt32() is not in a format that can be convertedto an int .

    When this happens, the computer will trace back through the method calls, looking fora handler that can handle this exception.

    Your first catch block (the one that takes an IndexOutOfRangeException ) will not do.

    The computer then looks at the second catch block. This one will do becauseFormatException is derived from Exception , so a FormatException instance can bepassed in as a parameter here.

    In the previous example, you have a third catch block listed in the code:catch{Console.WriteLine(Some other exception has occurred);}

    This is the most general catch block of all it does not take any parameter. Thereason this catch block is here is to catch exceptions thrown by other code that is notwritten in C# or is not even managed code at all.

    Downloaded from: www.onspot.pk