Exception Handling in C #

Source: Internet
Author: User
Tags exit count exception handling expression finally block garbage collection readline valid
Exception Handling in C #

Level Author
Intermediate Anonymous

What World抯 wrong with return codes?
Most programmers have probably written code that looked like this:
BOOL Success =callfunction ();
if (!success)
{
Process the error
}
This works okay, but every return value has to is checked for an error. If the above
was written as
CallFunction ();
Any error return would be thrown away. That's World抯 where Bugs come from.
There are many different models for communicating status; Some functions
May return an HRESULT, some could return a Boolean value, and others could use
Some other mechanism.
In the. NET Runtime World, exceptions are the fundamental method of han-dling
Error conditions. Exceptions are nicer than return codes because they can don't
be silently ignored.

Trying and catching
To deal with exceptions, the code needs to is organized a bit differently. The sections
of code that might throw exceptions are placed in a try block, and the code to handle
Exceptions in the try block is placed in a catch block. Here World抯 an example:


Using System;
Class Test
{
static int Zero = 0;
public static void Main ()
{
Watch for exceptions
Try
{
Int J =22/zero;
}
Exceptions that occur in a try are transferred here
catch (Exception e)
{
Console.WriteLine ("Exception" +e.message);
}
Console.WriteLine ("After Catch");
}
}


The try block encloses a expression that would generate an exception. In the case,
It would generate an exception known as Dividebyzeroexceptio. When the division
takes place, the. NET Runtime stops executing code and searches for a try block
Surrounding the "code in which" exception took place. When it finds a try block,
It then looks for associated catch blocks.
If it finds catch blocks, it picks the best one (more on how it determines which
One is best in a minute), and executes the code within the "Catch block." The code in
The catch block may process the event or rethrow it.
The example code catches the exception and writes out of the message this is
Contained within the exception object.
The Exception hierarchy
All C # Exceptions derive from the class named Exception, which are part of the Common
Language Runtime 1. When a exception occurs, the proper catch block is
Determined by matching the type of the exception to the name of the exception
mentioned. A catch block and an exact match wins off over a
exception. Returning to the example:
Using System;
Class Test
{
static int Zero = 0;
public static void Main ()
{
Try
{
Int J =22/zero;
}
Catch a specific exception
catch (DivideByZeroException e)
{
Console.WriteLine ("DivideByZero {0}", e);
}
Catch any remaining exceptions
catch (Exception e)
{
Console.WriteLine ("Exception {0}", e);
}
}
}
The catch block that catches the dividebyzeroexception are the more specific match,
and is therefore the one this is executed.
This example are a bit more complex:

Using System;
Class Test
{
static int Zero = 0;
static void Afunction ()
{
int j = 22/zero;
The following line is never executed.
Console.WriteLine ("In Afunction ()");
}
public static void Main ()
{
Try
{
Afunction ();
}
catch (DivideByZeroException e)
{
Console.WriteLine ("DivideByZero {0}", e);
}
}
}
What happens here?
When the division is executed, a exception is generated. The runtime starts
Searching for a try blocks in afunction (), but it doesn don't find one, so it jumps out of
Afunction (), and checks for a try in Main (). It finds one, and then looks for a catch
that matches. The catch block then executes.
Sometimes, there won don't is any catch clauses that match.
Using System;
Class Test
{
static int Zero = 0;
static void Afunction ()
{
Try
{
Int J =22/zero;
}
This exception doesn ' t match
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine ("Outofrangeexception:{0}", E);
}
Console.WriteLine ("In Afunction ()");
}
public static void Main ()
{
Try
{
Afunction ();
}
This exception doesn ' t match
catch (ArgumentException E)
{
Console.WriteLine ("ArgumentException {0}", e);
}
}
}
Neither the "Catch block" in afunction () nor the catch blocks in Main () matches the
Exception that World抯 thrown. When this happens, the ' exception is caught ' by the ' last
Chance "Exception handler. The action taken by this handler depends in how the
Runtime is configured, but it'll usually bring up a dialog box containing the Excep-tion
Information and halt the program.
Passing exceptions on to the Caller
It world抯 sometimes the case, that there World抯 wasn't much of that can being done as an exception
Occurs; It really has to is handled by the calling function. There are three basic
Ways to deal with this, which are named based on their result in the Caller:caller
Beware, Caller confuse, and Caller inform.
Caller beware
The The "way" is to merely not catch the exception. This are sometimes the right design
Decision, but it could leave the object in a incorrect state, causing the
Caller tries to use it later. It may also give insufficient information to the caller.
Caller confuse
The second way is to catch the exception, do some cleanup, and then rethrow
The exception:
Using System;
public class Summer
{
int sum = 0;
int count = 0;
float average;
public void Doaverage ()
{
Try
{
Average =sum/count;
}
catch (DivideByZeroException e)
{
Do some cleanup
Throw e;
}
}
}
Class Test
{
public static void Main ()
{
Summer Summer =new Summer ();
Try
{
Summer. Doaverage ();
}
catch (Exception e)
{
Console.WriteLine ("Exception {0}", e);
}
}
}
This is usually the minimal bar for handling exceptions; An object should always
Maintain a valid a exception.
This is called Caller confuse because while the ' object is ' in a valid
The exception occurs, the caller often has little to go on. In the case,
The exception information says that a dividebyzeroexception occurred somewhere
In the called function, without giving any insight into the details of the exception
Or how it might to be fixed.
Sometimes this is okay if the exception passes back obvious information.
Caller Inform
In Caller inform, additional information are returned for the user. The caught exception
is wrapped in a exception that has additional information.
Using System;
public class Summer
{
int sum = 0;
int count = 0;
float average;
public void Doaverage ()
{
Try
{
Average =sum/count;
}
catch (DivideByZeroException e)
{
Wrap exception in another one,
Adding additional context.
Throw (New DivideByZeroException (
"Count is zero in Doaverage ()", e));
}
}
}
public class Test
{
public static void Main ()
{
Summer Summer =new Summer ();
Try
{
Summer. Doaverage ();
}
catch (Exception e)
{
Console.WriteLine ("Exception:{0}", E);
}
}
}
When the dividebyzeroexception was caught in the doaverage () function, it is wrapped
In a new exception that gives the user additional information about what caused the
exception. Usually the wrapper exception is the same type as the caught exception,
But this might change depending in the model presented to the caller.
This program generates the following output:
Exception:System.DivideByZeroException:Count is zero in Doaverage ()--->
System.DivideByZeroException
At Summer.doaverage ()
At Summer.doaverage ()
At Test.main ()
Ideally, each function is wants to rethrow the exception would wrap it in a excep-tion
With additional contextual information.
user-defined Exception Classes
One drawback of the last example are that the caller can don't tell what exception
In the call to Doaverage () by looking at the type of the exception. To know
That's exception was because the count is zero, the expression message would
have to was searched for the ' string is zero '.
That would is pretty bad, since the user wouldn don't is able to the the text
Would remain the same in later versions of the class, and the class writer wouldn
Be able to change the text. In the, a new exception class can be created.
Using System;
public class Countiszeroexception:exceptio
{
Public Countiszeroexception ()
{
}
Public countiszeroexception (String message)
: Base (Message)
{
}
Public countiszeroexception (String message,exception inner)
: Base (Message,inner)
{
}
}
public class Summer
{
int sum = 0;
int count = 0;
float average;
public void Doaverage ()
{
if (Count ==0)
Throw (New Countiszeroexception ("Zero count in Doaverage"));
Else
Average =sum/count;
}
}
Class Test
{
public static void Main ()
{
Summer Summer =new Summer ();
Try
{
Summer. Doaverage ();
}
catch (Countiszeroexception e)
{
Console.WriteLine ("Countiszeroexception:{0}", E);
}
}
}

Doaverage () Now determines whether there would is an exception (whether count
is zero), and if so, creates a countiszeroexception and throws it.
Finally
Sometimes, when writing a function, there would be some cleanup this needs to be
Done before the function completes, such as closing a file. If An exception occurs,
The cleanup could be skipped:
Using System;
Using System.IO;
Class Processor
{
int count;
int sum;
public int average;
void calculateaverage (int countadd,int sumadd)
{
Count +=countadd;
Sum +=sumadd;
Average =sum/count;
}
public void Processfile ()
{
FileStream F =new FileStream ("Data.txt", FileMode.Open);
Try
{
StreamReader T =new StreamReader (f);
String line;
while (line =t.readline ())!=null)
{
int count;
int sum;
Count =int32.fromstring (line);
Line =t.readline ();
Sum =int32.fromstring (line);
Calculateaverage (count,sum);
}
F.close ();
}
Always executed before function Exit,even if an
Exception is thrown in the try.
Finally
{
F.close ();
}
}
}
Class Test
{
public static void Main ()
{
Processor Processor =new Processor ();
Try
{
Processor. Processfile ();
}
catch (Exception e)
{
Console.WriteLine ("Exception:{0}", E);
}
}
}

This is example walks through a file, reading a count and sum from a file and using it
To accumulate an average. What happens, however, if the the
File is a zero?
If This is happens, the division in Calculateaverage () would throw a dividebyzero-
Exception, which'll interrupt the file-reading loop. If the programmer had
Written the function without thinking about exceptions, the call to file. Close ()
Would have been skipped, and the file would have open.
The code inside the "finally" guaranteed to execute before the exit of
The function, whether there is a exception or not. By placing the file. Close () call
In the finally block, the file would always be closed.
Efficiency and overhead
In languages without garbage collection, adding exception handling are expensive,
Since all objects within a function must is tracked to make sure that they are
Properly destroyed if a exception is thrown. The required tracking code both
Adds execution time and code size to a function.
In C #, however, objects are tracked by the garbage collector rather than the
compiler, so exception handling are very inexpensive to implement and imposes little
Runtime overhead on the "exceptional case" doesn don't occur.
Design Guidelines
Exceptions should is used to communicate exceptional conditions. Don don't use them to
Communicate events that are expected, such as reaching the end of a file. In the
Normal operation of a class, there should be no exceptions thrown.
Conversely, Don don't use return values to communicate information that would
Be better contained in a exception.
If there World抯 a good predefined exception in the System namespace that describes
The exception condition Palm ne that'll make sense to the users of the class 梪 SE
That's one rather than defining a new exception class, and put specific information
In the message. If the user might want to differentiate one case from others where
That's same exception might occur, then that would is a good place for a new excep-tion
Class.
Finally, if code catches an exception this it isn don't going to handle, consider whether
It should wrap that exception with additional information before rethrowing it.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.