- Java Programming Basics
- Java Tutorial
- Java Overview
- Java Environment Setup
- Java Program Structure
- Java Basic Syntax
- Java First Program
- Java Constants
- Java Separators
- Java Keywords
- Java Data Types
- Java Data Types
- Java Integers
- Java Floating Point
- Java Characters
- Java Booleans
- Java Numbers
- Java Programming Variables
- Java Variables
- Java Variable Types
- Java Variable Scope
- Java Type Conversion
- Java Type Casting
- Java Auto Type Promotion
- Java Type Promotion Rules
- Java Programming Arrays
- Java Arrays
- Java One Dimensional Array
- Java Multidimensional Array
- Java Programming Operators
- Java Operators
- Java Arithmetic Operators
- Java Increment Decrement
- Java Bitwise Operators
- Java Left Shift
- Java Right Shift
- Java Relational Operators
- Java Boolean Logical Operators
- Java Ternary(?) Operator
- Java Operator Precedence
- Java Control Statements
- Java Decision Making
- Java if if-else if-else-if
- Java switch Statement
- Java Loops
- Java while Loop
- Java do-while Loop
- Java for Loop
- Java for-each Loop
- Java Nested Loops
- Java break Statement
- Java continue Statement
- Java Class Object Method
- Java Classes and Objects
- Java Class
- Java Object
- Java new Operator
- Java Methods
- Java Constructors
- Java this Keyword
- Java Stack
- Java Overloading Recursion
- Java Method Overloading
- Java Constructor Overloading
- Java Object as Parameter
- Java Call by Value Reference
- Java Returning Objects
- Java Recursion
- Java Modifier Types
- Java Encapsulate Poly String
- Java Encapsulation
- Java Polymorphism
- Java Nested Inner Class
- Java Strings
- Java Command Line Arguments
- Java Variable Length Arguments
- Java Inheritance Abstraction
- Java Inheritance
- Java super Superclass
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Abstraction
- Java Packages Interfaces
- Java Packages
- Java Access Protection
- Java Import Statement
- Java Interfaces
- Java Programming Exceptions
- Java Exception Handling
- Java try catch
- Java throw throws
- Java finally Block
- Java Built In Exceptions
- Java Exception Subclasses
- Java Chained Exceptions
- Java Multithreading
- Java Multithreading
- Java Thread Model
- Java Main Thread
- Java Create Thread
- Java Thread Priorities
- Java Synchronization
- Java Inter Thread Communication
- Java Suspend Resume Stop Thread
- Java Get Thread State
- Java Enum Autobox Annotation
- Java Enumerations
- Java Type Wrappers
- Java Autoboxing
- Java Annotation
- Java Marker Annotations
- Java Single Member Annotation
- Java Built In Annotations
- Java Type Annotations
- Java Repeating Annotations
- Java Data File Handling
- Java Files I/O
- Java Streams
- Java Read Console Input
- Java Write Console Output
- Java PrintWriter Class
- Java Read Write Files
- Java Automatically Close File
- Java Programming Advance
- Java Date and Time
- Java Regular Expressions
- Java Collections Framework
- Java Generics
- Java Data Structures
- Java Network Programming
- Java Serialization
- Java Send Email
- Java Applet Basics
- Java Documentation
- Java Programming Examples
- Java Programming Examples
Java Exception Subclasses
Even though the Java's built-in exceptions handle the most common errors, you will probably want to create your own exception types to
manage the situations specific to your applications. This is quite easy to do:
just define a subclass of Exception (a subclass of Throwable). Your subclasses do not need to actually implement anything, it is
their existence in the type system which allows you to use them as exceptions.
Java Exception Class
The Exception class does not define any methods of its own. It does, inherit those methods provided by the Throwable. Thus, all the exceptions, including those that you create, have the methods that defined by the Throwable available to them. They are shown in the upcoming table. You may also like to override one or more of these methods in exception classes that you create.
Exception defines the four public constructors, in which, the two constructors support the chained exceptions (you will learn about chained exceptions in the next chapter), and the other two constructors are shown here :
Exception() Exception(String msg)
The first form creates an exception which has no description. And the second form lets you to specify a description of the exception.
Even though specifying a description when an exception is created is often useful, sometimes it is better to override the method toString(). As the version of the toString() method defined by the Throwable (and inherited by Exception) is first displays the name of the exception followed by colon, which is then followed by your description. By overriding the method toString(), you can prevent the exception name and colon from being displayed. This makes for the cleaner output, which is desirable in some of the cases.
Methods Defined by Throwable
Here, the following table lists the methods defined by Throwable:
Method | Description |
---|---|
final void addSuppressed(Throwable exc) | Adds exc to the list of suppressed exceptions associated with the invoking exception. Primarily for use by the try-with-resources statement |
Throwable fillInStackTrace() | Returns a Throwable object that contains a complete stack trace. This object can be re-thrown |
Throwable getCause() | Returns the exception that underlies the current exception. If there is no underlying exception, null is returned |
String getLocalizedMessage() | Returns a localized description of the exception |
String getMessage() | Returns a description of the exception |
StackTraceElement[] getStackTrace | Returns an array that contains the stack trace, one element at a time, as an array of the StackTraceElement. The method at the top of the stack is the last method called before the exception was thrown. This method is found in the first element of the array. The StackTraceElement class gives your program access to information about each element in the trace, such as its method name |
final Throwable[] getSuppressed() | Obtains the suppressed exceptions associated with the invoking exception and returns an array that contains the result. Suppressed exceptions are primarily generated by the try-with-resources statement |
Throwable initCause(Throwable causeExc) | Associates causeExc with invoking exception as a cause of invoking exception. Returns a reference to the exception |
void printStackTrace() | Displays the stack trace |
void printStackTrace(PrintStream stream) | Sends the stack trace to the specified stream |
void printStackTrace(PrintWriter stream) | Sends the stack trace to the specified stream |
void setStackTrace(StackTraceElement elements[]) | Sets the stack trace to the elements passed in elements. This method is for the specialized applications, not normal use |
String toString() | Returns a String object containing a description of the exception. This method is called by println() when outputting a Throwable object |
Java Exception Subclass Example
Here this example program declares a new subclass of Exception and then uses the subclass to signal an error condition in a method. It overrides the method toString(), allowing a carefully plain and simple description of the exception to be displayed.
/* Java Program Example - Java Create Exception Subclasses * This program creates a custom exception type */ class MyException extends Exception { private int detail; MyException(int x) { detail = x; } public String toString() { return "MyException[" + detail + "]"; } } class JavaProgram { static void calculate(int x) throws MyException { System.out.println("Called calculate(" + x + ")"); if(x>10) throw new MyException(x); System.out.println("Normal exit"); } public static void main(String args[]) { try { calculate(1); calculate(30); } catch(MyException e) { System.out.println("Caught " + e); } } }
This example program defines a subclass of Exception named MyException. This subclass is preferably simple. As it has only a constructor plus an overridden the method toString() that displays the value of the exception. The class JavaProgram defines a calculate() method which throws MyException object. The exception is thrown when the calculate() method's integer parameter is greater than 10. The method main() sets up an exception handler for the MyException and, then calls the method calculate() with a valid value (less than 10) and an illegal one to show both paths by the code. Here is the output/result :
« Previous Tutorial Next Tutorial »