1.1. What Is an Exception?

To signal that an error has occurred during program execution, the .NET CLR (Common Language Runtime) uses exceptions, which are objects that are thrown (instantiated and passed up the call stack) in response to runtime errors. A runtime error is one that changes or interrupts the normal flow of execution in a program.

NOTE

You will often see the terms exception and error used interchangeably, although technically they are not the same thing. An error is simply any situation in which unwanted or unexpected results occur, while an exception is a specific object instantiated in response to a runtime error. However, as long as it's understood that you're talking about runtime errors, swapping these terms is usually not a problem.

Runtime errors may be caused by invalid input, corrupted or unavailable resources, or an attempt to perform an action that isn't normally allowed. These can originate from your own code, from code contained in a shared library (e.g., a .dll in your site's bin folder or in the GAC), or from the .NET Framework itself. Runtime errors are differentiated from compile-time errors, which are often syntax or typing mistakes that prevent a programming from being built or run at all; and logical errors, which are flaws in reasoning on the part of the programmer of which the runtime has no knowledge.

Let's take a moment to consider how runtime errors actually occur in practice. Consider the method shown in Listing 1, which takes a text entry supplied by the user and writes the entry to a text file.

Example 1. LogEntry method
protected void LogEntry(object sender, EventArgs e)
{
   string path = GetPathToLog();
   StreamWriter writer = File.AppendText(path);

   writer.WriteLine(DateTime.Now.ToString(CultureInfo.InstalledUICulture));
   writer.WriteLine("Entry: {0}", txtLogEntry.Text);
   writer.WriteLine("--------------------");
   writer.Dispose();
}

Listing 1 has a call to File.AppendText (which takes as an argument a string indicating the physical path to the file you want to append to), as well as several calls to the StreamWriter.WriteLine method. Now, stop for a moment and think about all the things that could go wrong here.

  • path could be an empty string.

  • path could be null.

  • path could be too long.

  • path could contain invalid characters.

  • path could be in an invalid format.

  • path could point to a file outside the web site.

  • path could point to a valid directory, but not a specific file.

  • The directory specified in path may not exist.

  • The file specified in path may not exist.

  • The file may be read-only.

  • The ASP.NET account may not have sufficient permissions on the directory.

  • The file may be locked by a previous process.

  • There could be a disk error while opening the file or writing to the disk.

  • Something could go wrong outside of the file I/O system — the computer's memory could suddenly become corrupted, for example.

If any of the above scenarios actually does take place, a runtime error will occur, and the CLR will throw an exception.

Exceptions offer several advantages over other traditional methods of runtime error notification. Exceptions halt program execution unless you deal with them in an appropriate manner, and thus do not allow invalid values to persist. Also, unlike cryptic error codes, the properties of an exception object describe an error completely. For example, the Message property tells you what the error is, and the StackTrace property tells you which methods were executing at the point the error occurred. You'll learn more about these and other exception properties in a moment.

1.1.1. The Exception Class

In .NET, exceptions inherit from System.Exception, which is the base class from which all exceptions are derived. The exceptions you'll need to handle in your applications fall into one of two general categories:

  • Application Exceptions — Are custom exceptions thrown from references that you use in your web site, such as a shared library or a Web service. These are occasionally derived from System.ApplicationException, but are most often derived directly from System.Exception.

  • System Exceptions — Generated by the CLR itself, which ultimately derive from System.SystemException.

The .NET CLR provides a rich set of standard runtime exceptions. Those of a general nature reside in the System namespace, while the more specialized ones live in the various namespaces to which they apply. For example, exceptions that deal with data access are found in System.Data; security exceptions are grouped into System.Security; and exceptions that pertain to files, directories, and streams reside in System.IO.

1.1.1.1. Property Members
  • Message (System.String) — A string that briefly describes the error in a (hopefully) plain, understandable way.

  • Source (System.String) — The name of the application or object in which the error occurred. Because of dynamic page compilation in ASP.NET, this isn't likely to be of much use to you when an error is thrown from a page, as the compiled name will appear as something like "App_Web_ntdu-dh0" rather than "MyPage.aspx." Information contained in the Source property is more useful for errors generated by precompiled libraries or the .NET Framework itself.

  • StackTrace (System.String) — A string that contains a list of all the methods that were in execution at the time the exception was thrown, with the most recent method call appearing first. Essentially, StackTrace shows you everything that was in process when the exception was thrown, starting from the original request. If the site is running in debug mode, the actual line number in the method where the error occurred is noted as well. This is invaluable for tracking down stubborn bugs.

  • InnerException (System.Exception) — For various reasons, while handling an exception, frameworks and libraries sometimes find it useful to "wrap" the exception — that is, to create and throw a new exception that provides more information or more precisely describes the original error, while preserving the original exception in the new exception's InnerException property. This creates a chain of nested exceptions through which you can drill down to find the original exception if necessary.

NOTE

When examining an exception in the debugger, it's usually very helpful to check if there is an InnerException that contains an earlier exception.

1.1.1.2. Method Members
  • GetType (returns System.Type) — Returns the runtime type of an exception. Exception type names always end with the word Exception.

  • GetBaseException (returns System.Exception) — As noted above, exceptions can be nested inside other exceptions. The GetBaseException method eliminates the need to drill down through a chain of InnerExceptions to find the first exception that was thrown. In other words, this method returns the one exception that is the root cause of all the exceptions in a chain — the one for which InnerException is null. If the InnerException of the exception on which this method is called is already null, that means that the current exception is the base exception, in which case, the current exception is returned.

  • ToString (returns System.String) — A concatenated and formatted string containing the values of Message, Source, and StackTrace.

The above properties are common to all exceptions. Some derived exception types may possess additional specialized properties. For example, ArgumentException contains a ParamName string that gets the name of the parameter that caused the exception, and SmtpException contains a StatusCode enumeration that gets the status code returned by the mail server when an e-mail message is transmitted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.107.89