Exception Class

Package: java.lang

Java provides a catchall exception class called Exception that all other types of exceptions are derived from. This class contains the methods that are useful when handling exceptions.

Constructors

Constructor

Description

Exception()

Creates a new Exception object with no error information.

Exception(String message)

Creates a new Exception object with the specified error message.

Methods

Method

Description

String getMessage()

Describes the error in a text message.

void printStackTrace()

Prints the stack trace to the standard error stream. (The stack trace lists all the threads and objects that are active when the exception occurs.)

String toString()

Returns a description of the exception. This description includes the name of the exception class, followed by a colon and the getMessage message.

Here’s a snippet of code that catches all exceptions and displays the exception’s description on the console:

try

{

// statements that might throw

// an exception

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.