Error-handling using exceptions

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Module 4: Statements and Exceptions. Overview Introduction to Statements Using Selection Statements Using Iteration Statements Using Jump Statements Handling.
Code Correctness, Readability, Maintainability Svetlin Nakov Telerik Corporation
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Topics Introduction Types of Errors Exceptions Exception Handling
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Chapter 8 Improving the User Interface
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
C# Programming: From Problem Analysis to Program Design1 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design 3 rd.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Chapter 11 Debugging and Handling Exceptions
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Chapter 12: Advanced Topics: Exception Handling Visual Basic.NET Programming: From Problem Analysis to Program Design.
Apply Sub Procedures/Methods and User Defined Functions
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
Chapter 12: Exception Handling
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Exceptions Handling Exceptionally Sticky Problems.
Object Oriented Software Development 8. Exceptions, testing and debugging.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 11 – Exception Handling
Debugging and Handling Exceptions
CNS 3260 C# .NET Software Development
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Throwing and catching exceptions
Part B – Structured Exception Handling
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

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, farid.naisan@mah.se

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 5.4. Who can detect this type of error, only those who are experts in the concepts implemented in the program. Farid Naisan

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

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

Logic Errors The division gives 12.5 of the exchanged type, while multiplication gives a result 800. 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 3.0. I get it – lacking parenthesis! Farid Naisan

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

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

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

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

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

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

A try-catch example using C# Farid Naisan

The same example in VB Farid Naisan

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

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

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

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

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 (http://msdn.microsoft.com/en-us/library/804f22sf.aspx). Farid Naisan

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

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

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

Test the custom exception Farid Naisan

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

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

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

Links Exceptions Custom Exceptions: http://msdn.microsoft.com/en-us/library/5b2yeyab(v=VS.100).aspx Custom Exceptions: http://msdn.microsoft.com/en-us/library/87cdya3t(v=vs.80).aspx Farid Naisan