Programming with Attributes

Sometimes you need to provide metadata about the capabilities of your code. This metadata is meant to tell other code that is inspecting your code (through reflection) specific things about what the code might do. This includes information for the .NET runtime, such as how you want your code compiled. There are many attributes available in the .NET Framework. You can also create your own, custom attributes to be applied to your code. In this case, you can write code to examine the metadata about your own application.

Declarative attributes can be applied to classes, properties, methods, parameters, and other elements inside your code. You can apply a single attribute or multiple attributes to an application. Some attributes also might take parameters to indicate additional information to the attribute code.

Note that, by convention, all attributes end with the word Attribute in their names, such as SerializableAttribute. You typically leave the word attribute off your declaration, however, because it is not required.

In C#, attributes are placed on code using square brackets ([]). For example, you can use the ConditionalAttribute to indicate to the compiler which code should be compiled based on environment variables or command-line options. You would apply this attribute to your code as shown.

C#

[System.Diagnostics.Conditional("DEBUG")]
public void EmployeeCalculationsTestMethod()
{
  //code that compiles in the debug version of the assembly
}

In Visual Basic, you decorate your code elements with an attribute by putting the attribute in angle brackets (<>) in front of the code element, as follows.

VB

<Conditional("DEBUG")> Public Sub EmployeeCalculationsTestMethod()
  'code that compiles in the debug version of the assembly
End Sub

Exception Handling

A lot of programming time is spent eliminating exceptions from our code. However, you can’t always eliminate all scenarios that might cause an exception. In these cases, you need a way to anticipate the exception and then, if possible, handle the exception in your code. There is where the Try...Catch...Finally construct comes into play.

You put a Try statement around a block of code you expect might cause an exception. You typically do so if you intend to handle the error. If you are not intending to handle the error, you can let the error bubble up to the calling code. Of course, you need to have an outer-error handler (or manager) inside your outer code to prevent errors from bubbling up to users in nasty ways.

When an exception actually occurs inside your Try block, execution is immediately passed to a Catch block. This might be a general catch of all errors or a catch meant for a specific exception type. The code inside the catch block is then meant to handle the error. Handling an error might include logging the error, sending it to a message system, or actually trying something different (or trying again using a jump statement) as the result of the error.

The following shows a basic example. Inside the Try block is a calculation that does division. This Try block has the possibility of raising an exception in the case where the division is done by zero. This condition raises the specific exception DivideByZeroException. There is a Catch block that consumes this (and only this) type of exception. You can add code to the Catch block to either eat the exception (do nothing) or process it somehow. Also, if you want to rethrow the exception after handling it, you can do that, too.

C#

try
{
  averageSales = salesToDate / avgRate;
}
catch (System.DivideByZeroException e)
{
  //handle the exception ...
  // if rethrowing use: throw;
}

VB

Try
  averageSales = salesToDate / avgRate

Catch ex As System.DivideByZeroException
  'handle the exception ...
  ' if rethrowing use: Throw
End Try

You can have multiple Catch blocks that are both specific and generic. Note that if no exception type is found in a Catch block, the exception is actually not handled but is bubbled up to the calling code (or to the runtime).

Note that you can also rethrow the error from your Catch block using the Throw keyword. If you do not rethrow the exception, the runtime assumes you have handled the error and moves on. You can also use throw anywhere in your application where you want to raise an exception.

There is also a Finally block that you can write. This bit of code goes after your Catch blocks and runs regardless of whether an exception is raised. That is, it will always run after the code execution path exits the try block, either as a normal exit, after an exception is raised, or a call has been made to return. In all cases, the Finally block will execute. It is useful for cleaning up any resources that might have been allocated inside the Try block.


Exception Filtering

Both Visual Basic 14 and C# 6.0 now allow exception filtering during your catch blocks. This allows you to interrogate properties of the exception and only enter the catch block if a condition is met. You implement this approach using an if statement at the end of your catch.


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

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