Presentation is loading. Please wait.

Presentation is loading. Please wait.

Error-handling using exceptions

Similar presentations


Presentation on theme: "Error-handling using exceptions"— Presentation transcript:

1 Error-handling using exceptions
.NET Programming Error-handling using exceptions Contents: Types of errors Minimizing errors by using control statements and the Debug class Exceptions, Throwing and catching exceptions Custom exceptions When writing code, it is for sure that it will have errors and issues. There are two issues that are important. First, eliminated sources of errors as much as possible already when you are programming. Divisions by zeros, roots of negative numbers, objects not created properly, file not found situations and so on. Secondly, your must write code in a way so you can find and correct errors easily. Your code should be maintainable. When a program crashes or work improperly because of such errors, it is very poor programming. Most of the errors sources can be handled using simple controls using if statements. Check so that a reference variable is not null before using it. This can be done using an if statement. It is null, don't perform the task which requires a valid object reference. Then there are situations that not under the control of a programmer. Errors that occur at runtime are not always predictable. Normally, things go will, but sometimes exceptional conditions prevail. For example, you write code to create a file, but the user selects a drive and a folder that she or he doesn't have a write access to. If your code does not handle such an exceptional situation, and it just goes on with its next instructions, the program obvious crashes. Farid Naisan,

2 Types of errors Three main types of errors: Compile-time errors,
Run-time errors Logical errors Compilation errors occur when the syntax of a programming language are not followed. Run-time errors occur when the program is executing and some invalid operation is performed. Logical errors are errors in the program causing wrong output. Testing, finding and fixing errors in an application are a high percentage of the development time and cost. Some sources of error: Data entry mistakes Hacker attacks, System failure Debugging and finding and fixing errors are every programmer's daily work. As a programmer, your job is to make sure that all types of errors , no matter if is the user who is careless about inputting the correct values, or if somebody tries with to be mean to your program or your own coding causes error. It is not easy to believe that an application can be totally a bug-free application, but this should be a vision for you as a programmer. There three types of errors: Compilation Errors, Run-time Errors and Logical errors. The compilation errors are those which the compiler detects, usually not abiding with the rules of the programming language – writing incorrect syntax. The C# and VB compilers usually come with suggestion for the problems. The runtime errors are occur when operations fail under execution, for example a division by zero is occurs or opening files fail. Most of these errors can be detected and correcting when the program is being tested. Logical errors are the most hard ones to find, as in this case the program works well and it does not go down, but the results produces are not correct. The program produces a result 5.04 but it should have been Who can detect this type of error, only those who are experts in the concepts implemented in the program. Farid Naisan

3 Example – Compile Errors
Both methods fail to compile due to Option Strict On Sub Test() Dim intNumber As Integer Dim amount As Decimal intNumber = amount / 25.0 'Narrowing not allowed double  int '… End Sub 'Compilation error – functions return type must be given Function DivideNumbers( ByVal numerator As Double, _ ByVal denominator As Double) Return numerator/ denominator 'denominator must be <> 0 End Function Another example: the denominator is 0 What to do: Put an If-statement before doing the division. An exception is an indication of a problem that occurs during a program’s execution. Exception handling enables applications to resolve exceptions. An exception is thrown when an error is not handled. A DivisionByZero exception is thrown when a division by zero takes places when the program is running. To handle an exception so the program can continue executing when an error occurs is known as "catching " the exception. Exceptions are thrown in code where the execution cannot be continued because of some exceptional condition. Farid Naisan

4 Run-time errors Valid code resulting in invalid conditions Bug-fix
Run time errors are caused by bad user input or from your coding. Bad user input: try to create a file on a write-protected folder Bugs in code: as in the slide: Object not created. Another example is indexing arrays with a value out of range. Do a lot of checking in your code. Check if an object is not null. What to do? Farid Naisan

5 Logic Errors The division gives 12.5 of the exchanged type, while multiplication gives a result Which one is correct? The program gives me 800 Dollars for my 100 SEK – Incredible! What to do: Test! Let me test with 5 and 5. Why 6.33, it should have given a value I get it – lacking parenthesis! Farid Naisan

6 Error handling Errors can be handled by providing sufficient check in the source code using the basic control structures, e.g. if-statement. Use the Debug.Assert method to place watchdogs Handle exceptions. Take the appropriate action depending on the situation. Compiler errors are no problem. In the first case, if it is the user, give error message, cancel the rest of execution or continue with some valued values. Run-time errors, think about all possible conditions and circumstances – Think about what if …. issues! The second situation, if the object "other" is not valid, what can be done? Not much here. You cannot call another constructor because you would nee to have the call as the first statement in this constructor. To handle this error and avoid problem, there is unfortunately one thing to do: other should simple not be nothing. It must be a valid reference variable! Is this if- check adequate? Not really, see the next example: Farid Naisan

7 Using the Debug.Assert Example
A better check statement. If you the test gets too much for you, make sure that you at least check so the other-object is not Nothing. Farid Naisan

8 Exceptions It is assumed that code executes normally, but some times exceptions may occur. Exception is when something goes out of control at run time. Do you recognize this type of a message. I am sure you do and as long as there are careless programmers and program testers you'll continue see such unpleasant messages. The first message at left is because of a bug in the program. The programmer's code tries to access an object in a collection with an index that is outside the boundaries of the list. The second error message, the one on the right side, is because of the user input. A user gives non-numeric value as input where a numeric value is expected. But it is actually the programmer to blame for this error. The programmer should have thought of this situation and performed appropriate input control. Another situation is displayed by the message box at the bottom of this slide. This error has occurred when the program have tried open a file and has not succeeded, may be because the user has chosen a wrong drive or a wrong file type, or the programmer has hardcoded a file does not exist on the user's machine. When such error occur, it is hard to trust the program and to continue with the execution is done at your own risk. The CLR is very intelligent and handles exceptions with the choices, continue or quit (as you see here) but in old days, these caused program crash and even caused the operating system to behave abnormally. All these messages are Exceptions that has been thrown – notice the terminology but are not handled in the code. All of these errors could be avoided If you don't trap these exceptions, the CLR takes care of them as shown here, giving users some options. Farid Naisan

9 Throw and catch an exception
An Exception in computer programming is an object that can be created when an exceptional event occurs The object is then filled with information about the event and then “thrown” from the situation to some other place in the code where the Exception is “caught”. When the Exception is caught, the information about the exceptional event can be used to remedy the situation . And in this way, the Exception that occurred is “handled". Unhandled errors may cause: Data corruption Application crash Other consequences (blocking resources, etc) An exception in simple terms is an notice from an object to CLR, and is an object that is derived from a class in .NET called just Exception (big E at the beginning). The terminology here is to say an xxx Exception is thrown when a certain exceptional situation occur. Even bug-free programs may have bugs Write code that is as "bug-free" as possible. Farid Naisan

10 Call Stack A call stack is a list of methods that has been executed by CLR to get to the current position in the program code. When debugging, this information is usually available and it can be traced back to the very first method which the method Main. When an exception is thrown, the normal step by step execution of the program is stopped. The Exception is propagated back (thrown) on the call stack until it reaches a catch statement. CLR goes through the stack and if it does not find an exception handler registered for the exception, the unhandled-exception for the current application domain is fired and the program could be terminated. Once an exception is thrown, the CLR begins the process of unwinding the execution stack iteratively, frame by frame.1 As it does so, it cleans up any objects that are local to each stack frame. At some point, a frame on the stack could have an exception handler registered for the type of exception thrown. Once the CLR reaches that frame, it invokes the exception handler to remedy the situation. If the stack unwinds completely and a handler is not found for the exception thrown, then the unhandled-exception event for the current application domain may be fired and the application could be aborted. In short, as each method is called throughout the execution of a program, a frame is built on the stack that contains the passed parameters and any local parameters to the method. The frame is deleted upon return from the method. However, as the method calls other methods, and so on, new frames are stacked on top of the current frame, thus implementing a nested call-frame structure. Farid Naisan

11 Mechanics of handling exceptions
VB try { ' This part of code might result in ' an Exception thrown and the step- ' by-step execution might stop } catch(Exception ex) ' The execution comes here only if ' an Exception is thrown ' in the try block above ' here. ' Corrective actions can/should be ' taken here. } finally ' The finally block is executed no ' matter an exception is thrown or ' not. Try ' Code Catch ex As Exception Finally End Try The parts of your code where there may occur situation at run time that causes the program to stop executing, must contain code to handle the situation. This is programmatically done by using a try-catch and finally block. The code that is placed inside the try block is guarded and if something goes wrong in this block at runtime, the catch block is executed. You can use more than one catch blocks. The finally block is executed always whether en exception occurs or not. Finally is optional. The try part is where you put code and try it. If it works well, that is great but if doesn't you catch the error in the catch block, take corrective actions and let the execution continue in a save way, instead of letting your application end. If you are using resources in the try block, release them in the finally block no matter an error occurs or not. More than one catch can be used. Finally is optional. Farid Naisan

12 A try-catch example using C#
Farid Naisan

13 The same example in VB Farid Naisan

14 The Using statement VB C#
The finally block should typically contain code for releasing resources, e.g. closing files, etc. to ensure that resources are released regardless of whether an exception was thrown or not. The resource must be an object that implements the Idisposable interface. VB An alternative way is to use the statement using which simplifies writing code. Instead of acquiring and using a resource in a try block and releasing it in the finally block, you can use the using statement which automatically releases the resource when it is no longer needed. C# Farid Naisan

15 Throwing an exception In addition to catching errors, you can raise errors in your code, i.e. you can throw errors. An exception can be thrown simply by using the throw statement. In the example here a standard exception is thrown. Custom exceptions can be thrown in the same way. If you add throw in a try block, the execution jumps directly to the catch block. Farid Naisan

16 Throwing your own exception
Using the keyword throw, you send back en error to the caller code with a new message. You can also send the original error. This is a case when you want to intercept an exception and throw your own exception back to the caller code. You can also optionally send the original exception. As you see in this example, first the general exception is caught. Then the exception FileNotFoundException is raised and sent back to the caller code together with the original exception as the inner exception. So the caller exception gets access to the original exception too. Using this technique, you can customize exceptions with a new message. Farid Naisan

17 Custom Exceptions The System.Exception and its derived classes, defined in the .NET Framework, are very useful classes and can be used in most cases. However for some situation, you might want to use more specific exception types related closely to a problem. You can provide proper information in such cases by creating a user-defined exception types. All exception must derive from the System.Exception. Custom exceptions are however recommended to inherit the ApplicationException class which in turn inherits the class Exception. You can then throw the exception in your code based on some condition. The user of the method can then catch the Exception and handle the situation. The .NET Framework has a number of standard Exception classes that cover many situations such division by zero, IndexOutOfRangeException, and so on. These you can catch and handle. You should of course use these but it may happen that you might be looking for exceptions that do not exist in the .NET Framework libraries. In such cases, you can write your own exceptions for use with specific situations- exceptions To write a custom exception class is very easy. Write a class that inherits from the System.Exception which is the base class for all exception classes. Alternatively, you can make your class to derive from the ApplicationException When you want to write your own Exception class with more specific information for a certain type of situation or a problem, create a class that derive from the System.Exception or ApplicationException. The ApplicationException is Using exception names containing the word Exception is a good programming style. Name it something appropriate and use the word Exception in the name as a good style. You can then throw the exception at those places in your code where it is necessary and catch the exception in other parts that calls the code which throws the exception. It is important that the user of a method throwing an exception knows about it – through good code documentation. Farid Naisan

18 Custom Exception – Best practice
Your custom exception should have the word Exception as a suffix in the name. Provide three constructors: A default constructor A constructor with a string parameter for information about the exception. A constructor that takes a string parameter and an inner exception parameter to get at original exception info. You can define extra parameters for passing more information. The system.exception has three constructors, one default constructor with no parameter. One that takes a string object. The string is provided by the programmer from the code and it should contain a user-friendly description of the reason for the exception. The third constructor is a reference to the original Exception object, the innerException. An exception that is thrown as a direct result of a previous exception should include a reference to the previous exception in the InnerException property. You can read more about this argument on MSDN ( Farid Naisan

19 Custom Exception Example
A custom exception should preferably be derived from the ApplicationException which in turn is derived from the class Exception. ApplicationException is thrown by the user code not by the .NET runtime (CLR). Example: Assume we have a class product that has a field name. For some reason, the name should not be longer than 50 chars. If it does, an exception is to be thrown. Assume that we will not allow product names longer that 50 characters and if the user of the program does that, we raise an error by throwing an exception. The .NET does not have an exception class that can handle this situation. Lets call this TooLongProductNameException. Using the ApplicationException as base class instead of Exception is a way to differentiate between exceptions defined by applications versus exceptions defined by the system. ApplicationExceptions are thrown by the code Farid Naisan

20 Custom exception example – create an exception class
A custom exception class with three constructors. Notice that this exception class is inheriting the ApplicationException to make a marking here that this exception is a user defined exception not an exception from the .NET Framework libraries. The class has three constructors, Farid Naisan

21 Throw an object of the custom exception
Throw the NameTooLongException based on a condition. Send back to the caller code an error exception if the length of the name of a product is longer than a certain max length. The throw statement here, includes the error message, a null value indicating that I don't want to send info about the original exception, because there is no original one here, and finally information about the length of the current product's name. Farid Naisan

22 Test the custom exception
Farid Naisan

23 VS's Debugger Visual Studio has a very advance but easy to use Debugger. Some quick keys to remember: F9 Toggle a breakpoint F5 Start a debug session F10 Step over F11 Step into Shift+F5: Cancel/Stop debug session Ctrl+F5 : Run application without debugging Farid Naisan

24 Some guidelines Where ever in your code, you suspect a source of error at run time to user input or otherwise, provide code to handle the situation to prevent unwanted behavior at runtime. Correct the error, or simply continue execution in a save way. Do not use exceptions to control the flow of code execution. Do not use exception where you can handle errors using ordinary control statements such if else. .NET defines a large number of exceptions, but the parent to all exceptions is the class Exception. Try to use the correct exception type but if you are unsure about the type of error you get, use an object of the general Exception class. A finally block is a good place for clean up code as it is always executed no matter an error occurs or not. You want to use exceptions in complex methods to divert the execution of your code. This is not a good idea and not a good programming style. And do not use exceptions where you can use if-else statements to handle errors. For example to handle division by zero, you can simply use an if statement to check that the denominator is not equal to zero. Exceptions are not for such purposes. They are to be used for other things than handling errors. Farid Naisan

25 Summary Software errors and bugs cost money, but they exist
Every good programmer takes cares of all the situations that can cause errors. Use simple ways using if-statements, Debug object, etc. of checking for possible error. When simple checking is not sufficient, use structured exception handling. You have these options: No error handling – CLR applies default error handling Catch all types of error using objects of the general Exception class. Use specific Exceptions that handles specific errors, such IndexOutOfRangeException. Write your own exception class – user defined exception class Although you may be very careful in your programming and do your best to produce code that is well planned and well designed, things still will go wrong the software is in use. The user may give wrong input, the operating system may lock resources, and drives may not be available for your files to save, the CD drive of the computer may be out of function and so on. Therefore, it is important that your code is prepared for such situation by handling exceptions. Exception handling using try-catch-finally has overhead costs so use them only where you cannot not apply simple if-else statements or other such ordinary code structures. Avoiding a division by zero can simply be coded using an if-statement - if the denominator is zero, cancel the calculation, give error message to user or other correct actions. Farid Naisan

26 Links Exceptions Custom Exceptions:
Custom Exceptions: Farid Naisan


Download ppt "Error-handling using exceptions"

Similar presentations


Ads by Google