Try Catch Statement

 Try Catch Statement – Exception Handling in Java


package practice;

public class TryCatchDemo {

    public static void main(String[] args) {

        try {
            int number = 30;
            System.out.println(number / 0);

        } catch (Exception e) {

            System.out.println("Something went wrong.");
        }

    }

}

🔍 Explanation:

  • number / 0 → causes an ArithmeticException (because you can’t divide by zero).

  • The program throws an exception during that line.

  • Instead of crashing, the program jumps to the catch block and prints:

⚠️ Why Use try-catch?

  • To prevent program crash when something goes wrong.

  • To handle errors gracefully.

  • Common examples: division by zero, file not found, null pointer, etc.

Output – “Something went wrong.”

When Number is divided by Zero , it will throw exception. That exception will be caught by Catch Statement and , “Something went wrong.” will be limited.