#7files and Exceptions
#7files and Exceptions
#7files and Exceptions
The File class from the System.IO namespace, allows us to work with files.
The File class has many useful methods for creating and getting information about files. For example:
In [ ]:
using System.IO; // include the System.IO namespace
In [2]:
using System.IO; // include the System.IO namespace
Hello World!
Exceptions
try - The try statement allows you to define a block of code to be tested for errors while it is being executed.
catch - The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
finally - The finally statement lets you execute code, after try...catch, regardless of the result.
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:
In [2]:
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
In [4]:
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}
There are many exception classes available in C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException,
etc
In [ ]:
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!");
}
}
// Output:-
// System.ArithmeticException: 'Access denied - You must be at least 18 years old.'