Exception Handling in C#


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Now let's see some code examples to better showcase the exception handling in C#

The below is an exercise that currently, when run, will throw a DivideByZeroException.

You should add the proper exception handling code so that the testing assertion can pass.

An exercise to handle the DivideByZeroException

The below is an example of using multiple catch blocks, in File reading program, where this will showcase how you should include the catch blocks from the most to least specific exceptions that might occur.

Check and run the code to see how the test will pass

Note that we could have used a finally block to dispose the Stream and StreamReader objects, however, since we know that Stream and StreamReader classes both implement the IDisposable Interface, then the cleaner and much better way to do through the using keyword.

Even if there is an exception raised from any of the above objects, the using keyword will dispose the opened stream object and the stream reader object.

Now in the below sample we include the keyword throw to raise a new exception of type MethodNotImplementedException, this exception is a custom created one, it inherits from the InvalidOperationException

Check and run the code to see how the test will pass
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content