logo
Учебник_ПОА

Try and Catch

The try and catch keywords are used together. Use try to enclose the block of code you are concerned might generate an exception, and catch to contain the code that will be executed if the exception occurs. In this example, a calculation creates a division by zero exception, which is then caught. Without the try and catch blocks, this program would fail.

class ProgramTryCatch

{

static void Main()

{

int x=0, y=0;

try

{

x = 10 / y;

}

catch (System.DivideByZeroException)

{

System.Console.WriteLine("There was an attempt to divide by zero.");

}

}

}

It's good programming practice to be specific about the type of exception your catch code is detecting. Each try can have multiple catch statements, each dealing with a different exception.