Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet52/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   48   49   50   51   52   53   54   55   ...   78
Bog'liq
C sharp

 Try-Catch Statement
To avoid crashing the program, the exceptions must be caught using a 
try-catch statement. This statement consists of a try block containing the 
code that may cause the exception and one or more catch clauses. If the 
try block successfully executes, the program will then continue running 
after the try-catch statement. However, if an exception occurs, the 
execution will then be passed to the first catch block able to handle that 
exception type.
try {
StreamReader sr = new StreamReader("missing.txt");
}
catch {
Console.WriteLine("File not found");
}
 Catch Block
Since the previous catch block is not set to handle any specific exception
it will catch all of them. This is equivalent to catching the System.
Exception class, because all exceptions derive from this class.
catch (Exception) {}
To catch a more specific exception, that catch block needs to be placed 
before more general exceptions.
catch (FileNotFoundException) {}
catch (Exception) {}
The catch block can optionally define an exception object that 
can be used to obtain more information about the exception, such as a 
description of the error.
Chapter 21 exCeption handling


123
catch (Exception e) {
Console.WriteLine("Error: " + e.Message);
}
 Exception Filters
Exception filters were added in C# 6.0 and allow catch blocks to include 
conditions. The condition is appended to the catch block using the when 
keyword. A matched exception will then only be caught if the condition 
evaluates to true, as in the following example.
try {
StreamReader sr = new StreamReader("missing.txt");
}
catch (FileNotFoundException e)
when (e.FileName.Contains(".txt")) {
Console.WriteLine("Missing file: " + e.FileName);
}
When using exception filters, the same exception type may appear in 
multiple catch clauses. Additionally, there are scenarios when a more general 
exception can be placed before more specific ones. In the next example, 
all exceptions are logged by calling a logging method as an exception filter. 
Because the method returns false, the general exception is not caught and 
thereby allows for another catch block to handle the exception.
using System;
using System.IO;
static class ErrorHandling
{
// Extension method
public static bool LogException(this Exception e)
Chapter 21 exCeption handling


124
{
Console.Error.WriteLine($"Exception: {e}");
return false;
}
static void Main()
{
try {
var sr = new StreamReader("missing.txt");
}
catch (Exception e) when (LogException(e)) {
// Never reached
}
catch (FileNotFoundException) {
// Actual handling of exception
}
}
}

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   48   49   50   51   52   53   54   55   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling