Junior — Middle
What methods of error handling and exceptional situations are you familiar with?
sobes.tech AI
Answer from AI
In Java, exceptions are used for error handling and exceptional situations. Main methods:
- try-catch: a block of code that may throw an exception, wrapped in
try, and exception handling occurs incatch. - finally: a block that always executes, regardless of whether an exception was thrown or not, usually for resource cleanup.
- throws: declares that a method may throw an exception, so that calling code can handle it.
- Creating custom exceptions: you can create classes that inherit from
ExceptionorRuntimeException.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Division by zero is not possible");
} finally {
System.out.println("The finally block always executes");
}