Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0197 try...catch...finally

try...catch statement is for exception handling. Its syntax is try { ... // exception may get thrown within execution of this block } catch (ExceptionA ex) { ... // handle exception of type ExceptionA } catch (ExceptionB ex) { ... // handle exception of type ExceptionB } finally { ... // cleanup code } Here is a demo. using System; class Test { static int Calc(int x) { return 10 / x; } static void Main() { try { int y = Calc(0); Console.WriteLine(y); } catch (DivideByZeroException ex) { Console.WriteLine("x cannot be zero"); } Console.WriteLine("program completed"); } } The output: x cannot be zero program completed