ErrorHandling in cSharp example

Mar 5, 2013 00:00 · 476 words · 3 minute read Programming C# example errorHandling

What is error handing ?

“Things can go wrong, and when they do, we as programmers are responsible for making sure that our code does what it needs to do” (clean code, Robert Martin).

Write your try-catch-finally first and provide enough context for your exception errors. It is always better to catch an exception rather than check the type or return null.

Raise an exception

Sometimes in after we catch the exception and logging it , we might need to raise an exception to terminate the process. In this case, we can use various exception types according to our needs.

raise exception

public void RaiseException() {
	throw new ArgumentException("This is RaiseException exception");
}

Multiple catches

We can have multiple catch block for a try but only the first one that matches with our exception will be raised. The priority is top to down .

try catch finally

public string DoSomething() {
	string exceptionMessage = string.Empty;
	try {
	    RaiseException();
	} catch (DivideByZeroException exception) {
	    exceptionMessage = "divide by zero";
	} catch(ArgumentException exception) {
	    exceptionMessage = "argument exception";
	} catch(Exception exception) {
	    exceptionMessage = "General exception";
	} finally {
	    exceptionMessage = exceptionMessage + " finally";
	}
	return exceptionMessage;
}

In other words, if the “Argument exception” block catch our error, the rest of the blocks will be ignored.

Bear in mind if you put your general catch block at the top the rest of your block will be unreachable, therefore it is always better to put the more specific one in the top.

Finally block

The finally block is always executed whether an exception raise or not . It is a good practice to clean the resources that GC doesn’t care about it in essence such as file stream or DB connections.

It is also possible to use “Using” statement to clean up the resources after code execution but bear in mind that we use it only for the type that implement from IDisposal interface.

Priority is with inner catch block If you have different level of try catch , your exception will be always catch with the closest one.

priority

public void DoSomethingMore() {
	try {
	    DoSomething();
	} catch (Exception) {
	    throw new Exception();
	}
}

In the code above the exception will be caught by ArgumentException block which is inside the DoSomething and never execute the DoSomethingMore catch block.

Custom exception

You can always make your custom exception. It should inherit from Exception class and have a Serializable attribute.

custom exception

[Serializable]
public class MyException : Exception {
        public MyException() { }
        public MyException(string message) : base(message) { }
        public MyException(string message, Exception inner) : base(message, inner) { }
        protected MyException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }
}

The code exists in “Insert Snippet => Visual C# =>Exception”

Download

Feel free to download the full source code of this example from my GitHub.