Back
Close

Exception Handling in C#

AramT
6,786 views

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
·// { autofold
using System;
namespace ExceptionHandling
{
public class CalculationHelper
{
// }
public static int Calculate10DividedBy(int value)
{
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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
·using System;
using System.IO;
namespace ExceptionHandling
{
public class FileHelper
{
public static string ReadFileContents(string path)
{
var data = "";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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
·using System;
namespace ExceptionHandling
{
public class ObjectHelper
{
public static T SerializeObject<T>(T obj)
{
throw new MethodNotImplementedException();
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants