Try-catch helps your program handle errors without crashing. It lets you catch problems and decide what to do next.
0
0
Try-catch execution flow in C Sharp (C#)
Introduction
When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When connecting to the internet and the connection might fail.
When converting user input to a number that might be invalid.
Syntax
C Sharp (C#)
try { // code that might cause an error } catch (Exception e) { // code to handle the error }
The try block contains code that might cause an error.
The catch block runs only if an error happens in the try block.
Examples
This catches a divide by zero error and prints a message.
C Sharp (C#)
try { int x = 10 / 0; } catch (DivideByZeroException e) { Console.WriteLine("Cannot divide by zero."); }
This catches an error when trying to use a null object.
C Sharp (C#)
try { string s = null; Console.WriteLine(s.Length); } catch (NullReferenceException e) { Console.WriteLine("Object was null."); }
Sample Program
This program tries to divide 5 by 0, which causes an error. The catch block catches it and prints a friendly message. The program then continues to run.
C Sharp (C#)
using System; class Program { static void Main() { try { Console.WriteLine("Start"); int a = 5; int b = 0; int c = a / b; // This causes an error Console.WriteLine("Result: " + c); } catch (DivideByZeroException) { Console.WriteLine("Oops! You tried to divide by zero."); } Console.WriteLine("End"); } }
OutputSuccess
Important Notes
If no error happens, the catch block is skipped.
You can have multiple catch blocks for different error types.
Use try-catch to keep your program running smoothly even when errors happen.
Summary
Try-catch lets you handle errors without stopping your program.
Code inside try runs first; if an error happens, catch runs.
This helps make your programs more reliable and user-friendly.