C# try catch

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

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:
try{...}
catch(System.Reflection.TargetInvocationException e)
{
	MessageBox.Show("test");
	...
}

Catch multiple exceptions:
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 © 2024  | Terms of Use | Privacy | Home