[C#] C# Files and Exceptions

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in the class “Programming 2”


Working With Files

The File class from the System.IO namespace, allows us to work with files:

using System.IO; // include the System.IO namespace

File.SomeFileMethod(); // use the file class with methods

The File class has many useful methods for creating and getting information about files. For example:

Method Description
AppendText() Appends text at the end of an existing file
Copy() Copies a file
Create() Creates or overwrites a file
Delete() Deletes a file
Exists() Tests whether the file exists
ReadAllText() Reads the contents of a file
Replace() Replaces the contents of a file with the contents of another file
WriteAllText() Creates a new file and writes the contents to it. If the file already exists, it will be overwritten

For a full list of File methods, go to Microsoft .Net File Class Reference.


Write To a File and Read It

In the following example, we use the WriteAllText() method to create a file named “filename.txt” and write some content to it. Then we use the ReadAllText() method to read the contents of the file:

using System.IO; // include the System.IO namespace

string writeText = "Hello World!"; // Create a text string
File.WriteAllText("filename.txt", writeText); // Create a file and write the content of writeText to it

string readText = File.ReadAllText("filename.txt"); // Read the contents of the file
Console.WriteLine(readText); // Output the content

// Output: Hello World!


Exceptions

When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).


try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

try
{
  // Block of code to try
}
catch (Exception e)
{
  // Block of code to handle errors
}

Consider the following example, where we create an array of three integers:

This will generate an error, because myNumbers[10] does not exist.

int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]); // error!

The error message will be something like this:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

If an error occurs, we can use try…catch to catch the error and execute some code to handle it.

In the following example, we use the variable inside the catch block (e) together with the built-in Message property, which outputs a message that describes the exception:

try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine(e.Message);
}

// Output: Index was outside the bounds of the array.

You can also output your own error message:

try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine("Something went wrong.");
}

// Output: Something went wrong.


Finally

The finally statement lets you execute code, after try…catch, regardless of the result:

try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine("Something went wrong.");
}
finally
{
  Console.WriteLine("The 'try catch' is finished.");
}

// Output:
// Something went wrong.
// The 'try catch' is finished.


The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception class. There are many exception classes available in C#:

  • ArithmeticException
  • FileNotFoundException
  • IndexOutOfRangeException
  • TimeOutException, etc
static void checkAge(int age)
{
  if (age < 18)
  {
    throw new ArithmeticException("Access denied - You must be at least 18 years old.");
  }
  else
  {
    Console.WriteLine("Access granted - You are old enough!");
  }
}

static void Main(string[] args)
{
  checkAge(15);
}

// Output: System.ArithmeticException: 'Access denied - You must be at least 18 years old.'

If age was 20, you would not get an exception:

checkAge(20);

// Output: Access granted - You are old enough!




Back to Top

See other articles in Category CS

Leave a comment