pascal exception handling

In Pascal, exception handling allows you to handle runtime errors and exceptional conditions in your program. You can use the try...except block to catch and handle exceptions.

Here is the basic syntax for exception handling in Pascal:

  // code that may throw an exception
  // code to handle the exception

Within the try block, you place the code that may raise an exception. If an exception occurs, the program jumps to the corresponding except block. You can have multiple except blocks to handle different types of exceptions.

Here is an example that demonstrates the usage of exception handling in Pascal:

program ExceptionHandlingExample;

  num1, num2, result: Integer;

    writeln('Enter two numbers: ');
    readln(num1, num2);

    if num2 = 0 then
      raise Exception.Create('Division by zero is not allowed.');

    result := num1 div num2;
    writeln('Result: ', result);
    on E: Exception do
      writeln('Exception occurred: ', E.Message);

In this example, the program asks the user to enter two numbers. If the second number is zero, it raises an exception with a custom error message. The exception is caught in the except block, and the error message is displayed.

You can also use different exception types to handle specific types of exceptions. For example, you can use EZeroDivide to handle division by zero errors specifically:

  on E: EZeroDivide do
    // code to handle division by zero errors

By using exception handling in Pascal, you can gracefully handle errors and exceptional conditions in your program, improving its reliability and robustness.