What are the different types of exceptions in Java?
In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions. Checked exceptions are subclasses of Exception that the compiler checks at compile time, requiring explicit handling. Unchecked exceptions are subclasses of RuntimeException and Error, which the compiler does not require to be handled.
How can I create a custom exception in Java?
To create a custom exception in Java, define a new class that extends `Exception` (for checked exceptions) or `RuntimeException` (for unchecked exceptions). Provide constructors matching those in the `Exception` class, with options for a default, a message, and a cause.
How does the try-catch block work in Java?
A try-catch block in Java is used to handle exceptions and prevent program crashes. The code that might throw an exception is placed inside the `try` block, while the `catch` block follows to handle specific exceptions. If the exception occurs, control is transferred to the appropriate `catch` block, allowing for graceful error handling. If no exception is thrown, the catch block is skipped.
What is the difference between checked and unchecked exceptions in Java?
Checked exceptions are verified at compile-time, requiring explicit handling with try-catch blocks or throws declarations. Unchecked exceptions, derived from RuntimeException, are not checked at compile-time and occur during runtime, often indicating programming errors such as logical flaws or bad states.
What is the purpose of the 'finally' block in Java exception handling?
The purpose of the 'finally' block in Java exception handling is to execute important code such as resource cleanup, regardless of whether an exception was thrown or not. It runs after the try-catch block, ensuring resources are released efficiently, even if an exception is not caught.