In Java, the built-in base class for handling exceptions is the Throwable
class, which is the parent class of both Error
and Exception
.
Throwable
is a superclass of all errors and exceptions in the Java language. It is the base class of the Java exception hierarchy and contains two subclasses: Error
and Exception
.
Error
represents serious problems that a reasonable application should not try to catch. Examples of Error
include the OutOfMemoryError
and the StackOverflowError
.
Exception
, on the other hand, represents exceptional conditions that a well-written application should catch. Examples of Exception
include the IOException
, the SQLException
, and the NullPointerException
.
You can catch and handle exceptions in Java by using the try-catch
block. The try
block encloses the code that might throw an exception, and the catch
block handles the exception if it occurs.
For example:
try { // code that might throw an exception } catch (Exception e) { // code to handle the exception }
You can also use the finally
block to specify code that should always be executed, regardless of whether an exception is thrown or caught.
try { // code that might throw an exception } catch (Exception e) { // code to handle the exception } finally { // code that should always be executed }