Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions & Error Handling

Similar presentations


Presentation on theme: "Exceptions & Error Handling"— Presentation transcript:

1 Exceptions & Error Handling
Christopher M. Pascucci 24-Nov-18

2 Errors and Exceptions An error is a bug in your program.
dividing by zero going outside the bounds of an array trying to use a null object or reference An exception is a problem whose cause is outside your program. trying to open a file that isn’t there running out of memory connecting or working with a database and SQL

3 What to do about errors and exceptions
An error is a bug in your program that occurs during execution of program code. It should be fixed. An exception is a problem that your program may encounter. The source of the problem is outside your program. Your program must be prepared to deal with it. The distinction between the two is that an error is an event and an exception is an object that was created by the event that contains where and when the error occurred.

4 Dealing with exceptions
Most exceptions arise when you are handling files or working with databases. A needed file may be missing. You may not have permission to write a database or file. A file or field may be the wrong type. Exceptions may also arise when you use someone else’s classes (or they use yours). You might use a class incorrectly. Incorrect usage should result in an exception.

5 Three approaches to error checking
Ignore all but the most important errors. The code is cleaner, but the program will misbehave when it encounters an unusual error. Do something appropriate for every error. The code is cluttered, but the program works better. You might still forget some error conditions. Do the normal processing in one place, handle the errors in another (this is the .NET way). The code is at least reasonably uncluttered. .NET tries to ensure that you handle every error.

6 The try statement .NET provides a control structure, the Try statement (also called the Try-Catch statement) to separate “normal” code from error handling: Try try this code and if an error occurs during this code it will be handled in the catch. Catch some exception handle the exception Catch some other exception (***optional) handle the exception Finally Optional code block that always executes after the try-catch Whether or not an exception occurred. End Try

7 Exception handling is not optional
As in other languages, errors usually just cause your program to crash. Other languages leave it up to you whether you want to handle exceptions. There are a lot of sloppy programs in the world. It’s normal for human beings to be lazy. .NET tries to force you to handle exceptions. This is sometimes a pain in the neck, but... the result is almost always a better program.

8 Error and Exception are Objects
When an error occurs, .NET throws an Exception and creates an Exception object for you to use. You can catch this object and try to recover. You can ignore the error (the program will crash). .NET also provides a global Err object that can be used like in previous versions of VB. Err.number – displays the error number. Err.Description – displays the error message.

9 A few common types of Exceptions
IO.IOException: a problem doing input/output. IO.FileNotFoundException: no such file. IO.EndOfStreamException: tried to read past the end of an i/o stream. NullReferenceException: tried to use a object that was actually null (this is a RuntimeException). InvalidCastException: tried to convert a non-numeric String to a number or some other invalid casting. IndexOutofRangeException: tried to access an array element using an index that is outside the bounds of an array. Data.DataException: error generated by using ADO.NET components. Data.SqlClient.SqlException: error generated by an SQL server. ArgumentException: generated when at least one of the arguments past to a method is not valid.

10 What to do about Exceptions
You have three choices: You can deal with it at the Page level using Try-Catch through out the page using the Page_Error event of the page You can deal with it at the Application level using the Application_Error procedure in the global.asax file. You can deal with it in the customError section of the web.config file. <customErrors mode="On"      defaultRedirect="myerror.htm">     <error statusCode="403"         redirect="authfailed.aspx"/>     <error statusCode="404"         redirect="filenotfound.aspx"/> </customErrors> 

11 Try-Catch-Finally After all the catch phrases, you can have an optional Finally phrase. Try Catch e as ExceptionType Catch e as AnotherExceptionType Finally End Try Whatever happens in Try and Catch, even if it does a Return statement, the Finally code will be executed. If no exception occurs, the Finally will be executed after the Try code. If an exception does occur, the Finally will be executed after the appropriate Catch code.

12 How the Try statement works
The code in the Try block part is executed. If there are no problems, the Catch phrases are skipped. If an exception occurs, the program jumps immediately to the first Catch clause that can handle that exception. Whether or not an exception occurred, the Finally code is executed.

13 Ordering the Catch phrases
A Try can be followed by many Catches. The first one that can catch the exception is the one that will catch the exception. Bad: Catch e As Exception Catch e As IO.IOException This is bad because IOException is a subclass of Exception, so any IOException will be handled by the first Catch. The second Catch phrase can never be used. Start by ordering Catches from the more specific down to the more general.

14 Constructing an Exception
Exceptions are classes; you can create your own Exception with new. Exception types have two constructors: one with no parameters, and one with a String parameter. But first, you should look through the predefined exceptions to see if there is already one that’s appropriate. Public Class NotEnoughPizzaException     Inherits System.ApplicationException     Public Sub New()     End Sub     Public Sub New(ByVal strMessage As String)         MyBase.New(strMessage)     End Sub End Class Try   Throw New NotEnoughPizzaException(_        "Better order more") Catch ex As NotEnoughPizzaException   Response.Write(ex.Message) End Try

15 The End… Additional Resources: Exception Hierarchy
Comprehensive List of Exceptions & Hierarchy


Download ppt "Exceptions & Error Handling"

Similar presentations


Ads by Google