
Exception Handling
In the previous chapter, we looked at functions. Despite the best efforts of programmers to write robust code, functions will, at some point, generate exceptions. This could be for a number of reasons, such as a missing file or folder, an empty or null value, the location can't be written to, or the user is denied access. So, with that in mind, in this chapter, you will learn about appropriate ways to use exception handling to produce clean C# code. First, we will start by looking at checked and unchecked exceptions with regards to arithmetic OverflowExceptions. We will look at what they are, why they are used, and some examples of them being used in code.
Then, we'll look at how we can avoid the NullPointerReference exception. After that, we'll look at implementing specific business rules for specific types of exceptions. With our fresh understanding of exceptions and exception business rules, we will set about building our own custom exceptions and then finish off by looking at why we should not use exceptions to control the flow of our computer programs.
In this chapter, we will cover the following topics:
- Checked and unchecked exceptions
- Avoiding NullPointerExceptions
- Business rule exceptions
- Exceptions should provide meaningful information
- Building your own custom exceptions
By the end of this chapter, you will have the skills to do the following:
- You will be able to understand what checked and unchecked exceptions are, and why they are in C#.
- You will be able to understand what an OverflowException is and how to trap them at compile time.
- You will know what NullPointerExceptions are and how to avoid them.
- You will be able to write your own custom exceptions that provide meaningful information to the customer and that aid you and fellow programmers to easily identify and resolve any issues that are raised.
- You will be able to understand why you should not use exceptions to control program flow.
- You will know how to replace business rule exceptions with C# statements and Boolean checks to control program flow.