Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Error Handling | Data Structures & File Handling
C# Beyond Basics

bookError Handling

You might have come across the term runtime error in previous chapters. A runtime error is an error which occurs while the program is running - hence the name "runtime" error.

Usually when a runtime error occurs, the program crashes or stops responding.

The compiler can help you by pointing out most of the errors in our code but runtime errors are mostly unpredictable and often depend on uncertain parameters.

For example, in case the file path passed into StreamReader is invalid or does not exist, it will give a runtime error and the program will crash. Therefore, we can often put such dangerous code into try-catch blocks to try some code, and in case it fails, we catch and deal with the error instead of causing the program to crash.

Following is the syntax of the try-catch block:

index.cs

index.cs

copy
1234567
try { // code to try } catch (Exception errorVar) { // code to handle error }

Here Exception is a keyword which represents the datatype Exception.

Example

index.cs

index.cs

copy
1234567891011121314151617
using System; using System.IO; class Program { static void Main(string[] args) { try { new StreamWriter("C:/a/random/path/that/does/not/exist.txt"); } catch(Exception error) { Console.WriteLine(error.Message); } } }
Note
Note

We can omit the (Exception error) part from the catch statement if we're not using error.

Following are some common cases where a runtime error can occur:

Division By Zero

index.cs

index.cs

copy
123456789101112131415161718
using System; class Program { static void Main(string[] args) { try { int a = 100; int b = 0; int result = a / b; } catch { Console.WriteLine("ERROR: Division by Zero."); } } }

Invalid Index of an Array or a List

index.cs

index.cs

copy
1234567891011121314151617
using System; class Program { static void Main(string[] args) { try { var exampleArray = new int[10]; Console.WriteLine(exampleArray[20]); } catch { Console.WriteLine("ERROR: The array index is out of bounds."); } } }

Key Not Found (for Dictionaries):

index.cs

index.cs

copy
123456789101112131415161718192021
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { try { Dictionary<string, string> myDict = new Dictionary<string, string> { { "key1", "value1" } }; Console.WriteLine(myDict["key2"]); } catch { Console.WriteLine("Error: Key not found"); } } }

The finally Block

There's also an option code block called finally which is executed after the catch block is executed:

index.cs

index.cs

copy
12345678910111213141516171819202122232425
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { try { Dictionary<string, string> myDict = new Dictionary<string, string> { { "key1", "value1" } }; Console.WriteLine(myDict["key2"]); } catch { Console.WriteLine("Error: Key not found"); } finally { Console.WriteLine("This line will show after the error"); } } }

1. What will be the output of the following program?

2. In C#, what is the purpose of the finally block?

3. Which of the following statements is true regarding the try-catch block in C#?

question mark

What will be the output of the following program?

Select the correct answer

question mark

In C#, what is the purpose of the finally block?

Select the correct answer

question mark

Which of the following statements is true regarding the try-catch block in C#?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 9

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Can you explain how the try-catch block works with an example?

What are some best practices for handling runtime errors?

Can you list other common runtime errors besides the ones mentioned?

Awesome!

Completion rate improved to 2.04

bookError Handling

Swipe to show menu

You might have come across the term runtime error in previous chapters. A runtime error is an error which occurs while the program is running - hence the name "runtime" error.

Usually when a runtime error occurs, the program crashes or stops responding.

The compiler can help you by pointing out most of the errors in our code but runtime errors are mostly unpredictable and often depend on uncertain parameters.

For example, in case the file path passed into StreamReader is invalid or does not exist, it will give a runtime error and the program will crash. Therefore, we can often put such dangerous code into try-catch blocks to try some code, and in case it fails, we catch and deal with the error instead of causing the program to crash.

Following is the syntax of the try-catch block:

index.cs

index.cs

copy
1234567
try { // code to try } catch (Exception errorVar) { // code to handle error }

Here Exception is a keyword which represents the datatype Exception.

Example

index.cs

index.cs

copy
1234567891011121314151617
using System; using System.IO; class Program { static void Main(string[] args) { try { new StreamWriter("C:/a/random/path/that/does/not/exist.txt"); } catch(Exception error) { Console.WriteLine(error.Message); } } }
Note
Note

We can omit the (Exception error) part from the catch statement if we're not using error.

Following are some common cases where a runtime error can occur:

Division By Zero

index.cs

index.cs

copy
123456789101112131415161718
using System; class Program { static void Main(string[] args) { try { int a = 100; int b = 0; int result = a / b; } catch { Console.WriteLine("ERROR: Division by Zero."); } } }

Invalid Index of an Array or a List

index.cs

index.cs

copy
1234567891011121314151617
using System; class Program { static void Main(string[] args) { try { var exampleArray = new int[10]; Console.WriteLine(exampleArray[20]); } catch { Console.WriteLine("ERROR: The array index is out of bounds."); } } }

Key Not Found (for Dictionaries):

index.cs

index.cs

copy
123456789101112131415161718192021
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { try { Dictionary<string, string> myDict = new Dictionary<string, string> { { "key1", "value1" } }; Console.WriteLine(myDict["key2"]); } catch { Console.WriteLine("Error: Key not found"); } } }

The finally Block

There's also an option code block called finally which is executed after the catch block is executed:

index.cs

index.cs

copy
12345678910111213141516171819202122232425
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { try { Dictionary<string, string> myDict = new Dictionary<string, string> { { "key1", "value1" } }; Console.WriteLine(myDict["key2"]); } catch { Console.WriteLine("Error: Key not found"); } finally { Console.WriteLine("This line will show after the error"); } } }

1. What will be the output of the following program?

2. In C#, what is the purpose of the finally block?

3. Which of the following statements is true regarding the try-catch block in C#?

question mark

What will be the output of the following program?

Select the correct answer

question mark

In C#, what is the purpose of the finally block?

Select the correct answer

question mark

Which of the following statements is true regarding the try-catch block in C#?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 9
some-alt