C# try catch

try{...}catch(){...}finally{...} is used for catching exceptions, and preventing program interruption.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
string file = "text.txt";
System.IO.FileInfo fileInf = new System.IO.FileInfo(file);
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream to read the file
System.IO.FileStream fs = fileInf.OpenRead();
try
{
    contentLen = fs.Read(buff, 0, buffLength);
    // Till Stream content ends
    while (contentLen != 0)
    {
        System.Console.WriteLine(buff);
        contentLen = fs.Read(buff, 0, buffLength);
    }
}
catch (System.Exception ex)
{
    System.Console.WriteLine(ex.Message);
}
finally
{
    fs.Close();
}

Catch the specific exception:
1
2
3
4
5
6
try{...}
catch(System.Reflection.TargetInvocationException e)
{
    MessageBox.Show("test");
    ...
}

Catch multiple exceptions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
try{
    WebBrowser wb = new WebBrowser();
    wb.ScriptErrorsSuppressed = true;
    ...
}
catch(System.Reflection.TargetInvocationException e)
{
    errorHandler(ex);
    ...
}
catch(System.Runtime.InteropServices.COMException e)
{
    errorHandler(ex);
    ...
}

Or:
try{
    WebBrowser wb = new WebBrowser();
    wb.ScriptErrorsSuppressed = true;
    ...
}
catch(Exception ex)
{
  if (ex is System.Reflection.TargetInvocationException)
  {...}
  else if (ex is System.Runtime.InteropServices.COMException)
  {...}
  throw;
}

endmemo.com © 2025  | Terms of Use | Privacy | Home