try-catch Block

Handling exceptions

5 min read

try-catch Block

The try-catch block is used to handle exceptions and prevent abnormal program termination.

Code Examples

Catching an exception

java
1
2try {
3    int result = 10 / 0;
4} catch (ArithmeticException e) {
5    System.out.println("Cannot divide by zero");
6}
7          

Use Cases

  • Error recovery
  • Input validation

Common Mistakes to Avoid

  • Catching generic Exception
  • Empty catch blocks