Errors will happen. The question is how will you deal with them? The QA Friday from 2015 Dec-11 talked about this question. This episode explains C# exceptions and how they are different from C++ exceptions.
When should you use exceptions in your code? You might find some guidance that tells you to place a try/catch or a try/catch/finally block around any method that can throw an exception. I advise you to start a try block for either or both of the following reasons:
- You know how to handle an exception either completely or partially. As long as you have some meaningful contribution to make if you were to catch a specific exception type, then go ahead and setup the try block and add your catch statement to catch that exception.
- You have some code that you want to make sure always runs either with to without an exception. Then setup the try block and add a finally statement so you can place your code in the finally block. This will run either after all the code in the try block finishes normally or after an exception is thrown and potentially caught by one of the exception handlers.
In C#, you can throw anything that derives from System.Exception including System.Exception itself. I advise against throwing System.Exception directly. It doesn’t provide any additional type information and creating your own type is just too easy. There are also many useful and recommended exception types already defined for you in the .Net Framework. Here are some of the common types:
- InvalidOperationException – Throw this type when you want to show that a method should not be called while the class instance is in a particular state.
- ArgumentException – Throw this when you find an argument passed to one of your methods that’s not right and not due to one of the next two scenarios.
- ArgumentNullException – Throw this when you find an argument passed to one of your methods that’s not right because it’s null.
- ArgumentOutOfRangeException – Throw this when you find an argument passed to one of your methods that’s not right because its value is either too small or too large.
- NullReferenceException – Don’t throw this. Just fix the problem. This exception represents a coding bug that needs to be fixed. You might want to catch this exception to log the problem.
- OutOfMemoryException – Don’t throw this exception either. If you catch this exception, then you might be able to recover by getting rid of memory you don’t need and trying the operation again. The computer system is likely very unstable at this point so you may not be able to recover.