Archive

Posts Tagged ‘Exceptions’

Learn C# – Handling Exceptions (4) – Custom Exceptions

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Handling Exceptions – Part 3 – Throwing Exceptions
  4. Handling Exceptions – Part 4 – Custom Exceptions

We met some common exception classes till now, and we even experienced throwing those exceptions by ourselves. That’s not always the case – we might want from time to time to throw our own exceptions, that will describe our own errors. For that purpose we should take a look first in the Exception class.

The Exception class

The basic Exception class is very simple, and contains some important properties:

  • Message – Contains details about the thrown exception.
  • Stack Trace – Contains details about all the methods involved.
  • InnerException – Sometimes contains details about the encapsulated exception.

There are some others, but those are the most useful. The constructor of the Exception class can accept custom message, so we can use that in order to supply our own exception:

void RegisterStudent(int age)
{
if (age < 18)
throw new Exception("Student can't be younger than 18 years old!");
}

This solution can feet our needs, but we usually don’t want to rely on strings to distinguish between exceptions. We will prefer something more strongly typed.

Custom Exceptions

The second solution for our desire will be to create custom exceptions. Custom exceptions are very simple to create, and it has only one rule: Inherit the base Exception class (or one of its childs). You can add whatever properties you want to your custom exception class, and use whatever constructor you’d like in the base class. Sometimes you won’t add any property at all – by creating specific type to describe the exception it might be enough. Let’s declare one:

public class StudentAgeException:Exception
{
public StudentAgeException(int age)
:base ("Age "+ age+" is not allowed. student age should be at least 18 years old")
{

}
}

And now we’ll use it:

void RegisterStudent(int age)
{
if (age < 18)
throw new StudentAgeException(age);
}

In the above example we declare new custom exception, that accept int parameter in its constructor and pass a message to the base constructor describing the issue. Whoever get’s the exception don’t need to rely on the message to understand the problem, since the problem is also identified by the type of the exception itself. That way is much more strongly typed and safe, since the caller can now create specific catch block to catch only StudentAgeException, and handle this exception in more specific way.

In the Next post we’ll describe the finally block, which will be the last part of our series.

Learn C# – Handling Exceptions – Part 2

  1. Handling Exceptions – Part 1 – Basic Try / Catch
  2. Handling Exceptions – Part 2 – Catch block
  3. Learn C# – Exceptions Handling – Part 3 – Throwing Exceptions

In this part we goanna look in more depth in the try/catch clauses.

The simple case of try/catch, as we seen in the last post, can catch any exception occurred in the try block, and let us handle it in our catch block.

try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!
//Notice: "Done" wasn't printed to the console, since the exception was thrown before.

Let’s see some other options available for the try / catch.

Exception details

Not only the catch block can catch our exceptions, but also supply details about the caught exception, like this:

try
{
  //some exception
}
catch (Exception ex)
{
  //ex is an instance of the Exception class, with properties that supply many details about the exception.
}

The Exception class is the base class for any exception used in the .NET framework, and will be described in details later. For now, just note that this class contains some properties with details about the exception, as error message, where the exception originally occurred, etc.

Handle specific exception

The Exception class is not the only class in .NET used to handle exceptions. Lot’s of other classes are used, and all share one important behavior: They all inherit (directly or indirectly) from the base Exception class. NullReferenceException, DivideByZeroException and many others are all classes that have the same goal – handling exceptions. the difference between them is only the exception type, and sometimes, the details supplied.

specifying specific exception class in the brackets after the catch keyword will result catching only exceptions from this specific type. catch block without any type defined – will catch any exception. For example:

try
{
  int x = 0;
  int y = 10 / x;
}
catch (DivideByZeroException ex)
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!

In the above example, any other exception do not get caught (and if the program won’t find any suitable exception handler – it will probably crash). Notice that unlike method parameters, the ex used as a parameter name for the DivideByZeroException instance is not mandatory, and if you not going to use the ex properties, but only want to limit the exception types been caught, you don’t need to declare ex.

Handling some specific exceptions

The above technique of handling one specific exception, can be multiplied to more than one specific exception, like this:

try
{
 int x = int.Parse(Console.ReadLine());
 int y = 10 / x;
}
catch (DivideByZeroException ex)
{
 Console.WriteLine("Divide by zero exception was caught");
}
catch (FormatException ex)
{
 Console.WriteLine("Format exception was caught");
}

Now we handle two different exceptions – one for the DivideByZero and other for the Format. Whichever occurs first will cause his own catch clause to be executed.

One important thing need to be taken in consideration when declaring multiple exception handlers – The order of the catch clauses. Let’s have a look in some example:

try
{
 int x = int.Parse(Console.ReadLine());
 int y = 10 / x;
}
catch (Exception ex)
{
 Console.WriteLine("Divide by zero exception was caught");
}
catch (FormatException ex)
{
 Console.WriteLine("Format exception was caught");
}

This Example will cause compile-time error. The first catch declares the base Exception class as the type, and the second one declare the FormatException. Since all exception inherit from the base Exception class, any exception that will be thrown in the try block will be considered to be general Exception, so it will be caught in the first catch. Hence, the second catch block will never be called.

In the next post we’ll try to throw some exception by ourselves!

Categories: C#, Learn C# Tags: , , , ,

Learn C# – Handling Exceptions – Part 1

  1. Handling Exceptions – Part 1
  2. Handling Exceptions – Part 2

Let’s start with three basic assumptions:

  1. Developers usually don’t think about all possibilities.
  2. Users are not always friendly.
  3. A good program should handle any situation.

And that brings us to our subject: Handling exceptions.

Exception is any problem that the application hasn’t learned to deal with. Wrong input from the user can cause exception, as well as wrong mathematical operation, or sometimes the inability to connect to the internet when network is down. Since every application need to know exactly what to do anytime – when it doesn’t / can’t – exception been thrown.

Here are some examples:

int myNumber = int.Parse(Console.ReadLine());
//This code can optionally throw exception, if the user input can't be parsed to integer.

 

int x = 0;
int y = 10 / x;
//this code will throw exception anyway, because dividing by zero is not allowed!

 

File.Delete("some path to non-exist file");

Exceptions aren’t bad things by themselves, but if we won’t handle them carefully, they may crash our program, and we don’t want this to happen, right?

In order to handle exception we can use the try/catch clauses, like this:

try
{
  //here is block of code that potentially can throw exception
}
catch
{
  //if exception will be thrown above, this code will be excuted
}

Any exception that will be thrown in the “try” block, will cause immediate transition to the “catch” block. The rest of the code in the try block that hasn’t been executed yet – won’t be executed anymore. here is an example:

try
{
  int x = 0;
  int y = 10 / x;
  Console.WriteLine("Done");
}
catch
{
  Console.WriteLine("Error!!");
}
//OUTPUT:Error!!
//Notice: "Done" wasn't printed to the console, since the exception was thrown before.

In the next posts we goanna cover exception handling in more depth.

Categories: C#, Learn C# Tags: , , , ,
%d bloggers like this: