Exception Handling in C#

AramT
1,380 views

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
1
9
10
11
12
13
14
15
16
17
18
·// {...}
public static int Calculate10DividedBy(int value)
{
return 10 / value; //if the value is 0, this will throw a DivideByZeroException, so to fix it, handle the exception and return a int.MaxValue when exception is caught
}
// {
}
}
// }
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
·using System;
using System.IO;
namespace ExceptionHandling
{
public class FileHelper
{
public static string ReadFileContents(string path)
{
var data = "";
try
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (var file = new StreamReader(stream))
{
data = file.ReadToEnd();
}
}
}
catch (FileNotFoundException ex)
{
//Log the exception message from ex object
//Return a graceful message back to the caller
data = "Couldn't find file. Make sure it exists in the specific path";
}
catch (IOException ex)
{
//Log the exception message from ex object
//Return a graceful message back to the caller
data = "Unable to read from file";
}
catch (Exception ex)
{
//Log the exception message from ex object
//Return a graceful message back to the caller
data = "Something went wrong";
}
return data;
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
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
1
2
3
4
5
6
7
8
9
10
11
12
·using System;
namespace ExceptionHandling
{
public class ObjectHelper
{
public static T SerializeObject<T>(T obj)
{
throw new MethodNotImplementedException();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content