Skip to content
C

try-catch

try-catch is used to handle exceptions gracefully. Code that might cause a problem is placed inside a try block, and the code to handle that problem, if it occurs, is placed inside a matching catch block.


1. What is try-catch?

try-catch is used to handle exceptions gracefully. Code that might cause a problem is placed inside a try block, and the code to handle that problem, if it occurs, is placed inside a matching catch block.

2. Why is it used?

It prevents a program from crashing suddenly when something goes wrong. Instead, the catch block can display a helpful message or take an alternative action, keeping the rest of the program running smoothly.

3. Real-Life Example

Think of a safety net under a tightrope walker. If the walker (the risky code in try) slips, the safety net (catch) catches them, preventing a complete disaster, and the show can continue.

4. Syntax

java
try { // risky code } catch (ExceptionType e) { // code to handle the exception }

5. Example Program

java
public class TryCatchDemo { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } } }

Output:

Cannot divide by zero!

6. Key Points to Remember

  • Only the code genuinely at risk of throwing an exception needs to be inside try.
  • A try block can have multiple catch blocks to handle different exception types differently.
  • If no matching catch handles the thrown exception, the program still crashes with an error trace.