C#
try
{
}
catch (type name)
{
}
Example
C#
// Step 1. Start of the program
StreamReader stream = null;
try
{
// Step 2. Open the file
stream = new StreamReader("D:\\12345.txt");
// Step 3. File opened
}
catch (Exception e)
{
// Step 4. Section catch(Exception)
// show the error on the screen
Console.WriteLine(e.Message);
// close the file in case of an error
if (stream != null)
stream.Close();
}
// Step 5. End of the program
The program is carried out in steps:
Step 1. Start of the program
Step 2. Open the file
Step 4. Section catch(Exception)
On the screen we will see: Could not find file 'D:\12345.txt'.
Step 5. End of the program
Note 1
If the exception type does not match the type in catch the exception will not be handled and the program will crash.
Note 2
If we write
catch(Exception e
)
{
}
then we will handle any exception.
Exception this is the base class for all exceptions.