Explain structured exception handeling with example.
In : BSc IT Subject : Web Application Development - ASP.NETStructured Exception Handling is a way to handle runtime errors in a controlled manner using predefined blocks
It prevents the application from crashing and allows you to manage errors gracefully.
Blocks:
try: Contains code that might cause an error.catch: Handles the error if one occurs.finally: (Optional) Executes always — for cleanup (e.g., closing files, connections).
Example (C# in ASP.NET):
try
{
int num1 = int.Parse(txtNumber1.Text);
int num2 = int.Parse(txtNumber2.Text);
int result = num1 / num2;
lblResult.Text = "Result: " + result;
}
catch (FormatException)
{
lblResult.Text = "Please enter valid numbers.";
}
catch (DivideByZeroException)
{
lblResult.Text = "Cannot divide by zero.";
}
catch (Exception ex)
{
lblResult.Text = "An error occurred: " + ex.Message;
}
finally
{
// This runs no matter what
txtNumber1.Text = "";
txtNumber2.Text = "";
}
- Prevents app crashes on errors.
- Helps identify and handle different types of exceptions.
- Ensures resources are cleaned up properly.