Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Exception Handling

Java Exception Handling

In Java, exception handling is an important programming concept used to handle errors or exceptional situations that may occur during program execution.

Exceptions are some errors in a program, but not all errors are exceptions, and errors can sometimes be avoided.

For example, if your code is missing a semicolon, the result at runtime will indicate an error java.lang.Error. If you use System.out.println(11/0), then it is because you used 0 as the divisor that a java.lang.ArithmeticException will be thrown.

There are many reasons why exceptions occur, usually including the following major categories:

Some of these exceptions are caused by user errors, some by program errors, and others by physical errors.

To understand how Java exception handling works, you need to master the following three types of exceptions:

} catch (IOException e) { // Code to handle the exception }

or:

public void readFile() throws IOException {
// Code that might throw IOException
}

} catch (NullPointerException e) { // Code to handle the exception }

Java provides the following keywords and classes to support exception handling:


The Hierarchy of the Exception Class

All exception classes are subclasses inherited from the java.lang.Exception class.

The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable has another subclass, Error.

Java programs usually do not catch errors. Errors generally occur during serious failures and are outside the scope of Java program handling.

Error is used to indicate errors that occur in the runtime environment.

For example, JVM out of memory. Generally, a program does not recover from errors.

The Exception class has two main subclasses: the IOException class and the RuntimeException class.

Among Java's built-in classes (explained later), most commonly used checked and unchecked exceptions are included.


Java Built-in Exception Classes

The Java language defines some exception classes in the java.lang standard package.

Subclasses of the standard runtime exception classes are the most common exception classes. Since the java.lang package is loaded by default into all Java programs, most exceptions inherited from the runtime exception classes can be used directly.

Java also defines some other exceptions based on various libraries. The table below lists Java's unchecked exceptions.

exception Description
ArithmeticException Thrown when an exceptional arithmetic condition occurs. For example, when an integer is "divided by zero", an instance of this class is thrown.
ArrayIndexOutOfBoundsException Exception thrown when an array is accessed with an illegal index. The index is illegal if it is negative or greater than or equal to the array size.
ArrayStoreException Exception thrown when attempting to store an object of the wrong type into an object array.
ClassCastException Thrown when an attempt is made to cast an object to a class of which it is not an instance.
IllegalArgumentException Exception thrown to indicate that an illegal or inappropriate argument has been passed to a method.
IllegalMonitorStateException Exception thrown to indicate that a thread has attempted to wait on an object's monitor, or to notify other threads waiting on an object's monitor without itself specifying a monitor.
IllegalStateException Signal generated when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the appropriate state required by the requested operation.
IllegalThreadStateException Exception thrown when a thread is not in the appropriate state required by the requested operation.
IndexOutOfBoundsException Indicates that a sort index (such as for an array, string, or vector) is out of range and is thrown.
NegativeArraySizeException Thrown if an application attempts to create an array of negative size.
NullPointerException When an application attempts to use null where an object is required, this exception is thrown
NumberFormatException Thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format.
SecurityException Exception thrown by the security manager to indicate a security violation.
StringIndexOutOfBoundsException This exception is thrown by the String method and indicates that the index is either negative or beyond the size of the string.
UnsupportedOperationException Thrown when the requested operation is not supported.

The table below lists the checked exception classes defined by Java in the java.lang package.

exception Description
ClassNotFoundException Thrown when an application attempts to load a class and cannot find the corresponding class.
CloneNotSupportedException When Object the clone A method clones an object, but the object's class cannot implement Cloneable the interface, this exception is thrown.
IllegalAccessException Thrown when access to a class is denied.
InstantiationException When attempting to use the Class the newInstance method to create an instance of a class, and the specified class object cannot be instantiated because it is an interface or an abstract class, this exception is thrown.
InterruptedException Thrown when one thread is interrupted by another thread.
NoSuchFieldException The requested variable does not exist
NoSuchMethodException The requested method does not exist

Exception Methods

The following list shows the main methods of the Throwable class:

No. Method and Description
1 public String getMessage()
Returns detailed information about the exception that occurred. This message is initialized in the constructor of the Throwable class.
2 public Throwable getCause()
Returns a Throwable object representing the cause of the exception.
3 public String toString()
Returns a short description of this Throwable.
4 public void printStackTrace()
Prints this Throwable and its backtrace to the standard error stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing the stack trace. The element at index 0 represents the top of the stack, and the last element represents the bottom of the method call stack.
6 public Throwable fillInStackTrace()
Fills the Throwable object's stack trace with the current call stack, adding to any previous information in the stack trace.

Catching an Exception

You can catch exceptions using the try and catch keywords. The try/catch block is placed where an exception may occur.

The code in the try/catch block is called protected code. The syntax for using try/catch is as follows:


try
{
   // Program code
}catch(ExceptionName e1)
{
   //Catch 块
}

A catch statement contains a declaration of the exception type to catch. When an exception occurs in the protected block, the catch block after try is checked.

If the exception that occurs is included in a catch block, the exception is passed to that catch block, just like passing a parameter to a method.

Example

In the example below, an array with two elements is declared; when the code tries to access the fourth element of the array, an exception will be thrown.

ExcepTest.java file code:

//

File name: ExcepTest.java

import

java

.

io

.*;

public

class

ExcepTest

{

public

static

void

main

(

String

args

[

]

)

{

try

{

int

a

[

]

=

new

int

[

2

]

;

System

.

out

.

println

(

"

Access element three :

"

a

[

3

]

)

;

}

catch

(

ArrayIndexOutOfBoundsException

e

)

{

System

.

out

.

println

(

"

Exception thrown :

"

e

)

;

}

System

.

out

.

println

(

"

Out of the block

"

)

;

}

}

The output of the above code after compilation and execution is as follows:


Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks

A situation where a try block is followed by multiple catch blocks is called multiple catch.

The syntax of a multiple catch block is as follows:

try

{

//

Program code

}

catch

(

Exception type

1

Exception variable name

1

)

{

//

Program code

}

catch

(

Exception type

2

Exception variable name

2

)

{

//

Program code

}

catch

(

Exception type

3

Exception variable name

3

)

{

//

Program code

}

The code segment above contains 3 catch blocks.

You can add any number of catch blocks after a try statement.

If an exception occurs in the protected code, the exception is thrown to the first catch block.

If the data type of the thrown exception matches ExceptionType1, it will be caught here.

If it does not match, it is passed to the second catch block.

And so on, until the exception is caught or passes through all catch blocks.

Example

This example shows how to use multiple try/catch.

try

{

file

=

new

FileInputStream

(

fileName

)

;

x

=

(

byte

)

file

.

read

(

)

;

}

catch

(

FileNotFoundException

f

)

{

//

Not valid!

f

.

printStackTrace

(

)

;

return

1

;

}

catch

(

IOException

i

)

{

i

.

printStackTrace

(

)

;

return

1

;

}


Combined Catch of Multiple Exceptions

Starting from Java 7, a more concise syntax was introduced — combined catching of multiple exceptions, which allows handling several unrelated (non-inherited) exceptions in a single catch block.


try {
    // Code that might throw multiple different types of exceptions
} catch (异常类型1 | 异常类型2 | 异常类型3 异常变量) {
    // Unified processing
}

Note:

Exceptions such as the following that do not inherit from each other may throw both SQLException and IOException:

Example

try

{

   

// May throw both SQL and IO exceptions

    doSomething

(

)

;

}

catch

(

SQLException

|

IOException

e

)

{

   

System

.

out

.

println

(

"A SQL or IO exception occurred!"

)

;

    e.

printStackTrace

(

)

;

}

Incorrect example (cannot combine parent-child class exceptions):


// Incorrect way!
catch (FileNotFoundException | IOException e) {
    // Will cause a compilation error because FileNotFoundException is a subclass of IOException
}

FileNotFoundException is a subclass of IOException, so this approach is actually illegal and will cause a compilation error.


The throws/throw Keywords

In Java, the throw and throws keywords are used for handling exceptions.

The throw keyword is used to throw an exception in the code, while the throws keyword is used in a method declaration to specify the exception types that may be thrown.

The throw Keyword

The throw keyword is used to throw an exception in the current method.

Normally, when the code reaches a certain condition under which it cannot continue normal execution, you can use the throw keyword to throw an exception to inform the caller of the current code's execution state.

For example, in the code below, the method checks whether num is less than 0; if so, it throws an IllegalArgumentException.

Example

public

void

checkNumber

(

int

num

)

{

 

if

(

num

<

0

)

{

   

throw

new

IllegalArgumentException

(

"Number must be positive"

)

;

 

}

}

The throws Keyword

The throws keyword is used in a method declaration to specify the exceptions the method may throw. When the method internally throws an exception of the specified type, that exception is passed to the code that called the method and handled there.

For example, in the code below, when an IOException occurs inside the readFile method, that exception will be passed to the code calling the method. In the calling code, the IOException must be caught or declared to be handled.

Example

public

void

readFile

(

String

filePath

)

throws

IOException

{

 

BufferedReader

reader

=

new

BufferedReader

(

new

FileReader

(

filePath

)

)

;

 

String

line

=

reader.

readLine

(

)

;

 

while

(

line

!=

null

)

{

   

System

.

out

.

println

(

line

)

;

    line

=

reader.

readLine

(

)

;

 

}

  reader.

close

(

)

;

}

A method can declare that it throws multiple exceptions, separated by commas.

For example, the method below declares that it throws RemoteException and InsufficientFundsException:

import

java

.

io

.*;

public

class

className

{

public

void

withdraw

(

double

amount

)

throws

RemoteException

,

InsufficientFundsException

{

//

Method implementation

}

//

Remainder of class definition

}


The finally Keyword

The finally keyword is used to create a block of code that executes after the try block.

The code in the finally block is always executed regardless of whether an exception occurs.

In the finally block, you can run cleanup and other finalization statements.

The finally block appears at the end of the catch block; the syntax is as follows:

try

{

//

Program code

}

catch

(

Exception type

1

Exception variable name

1

)

{

//

Program code

}

catch

(

Exception type

2

Exception variable name

2

)

{

//

Program code

}

finally

{

//

Program code

}

Example

ExcepTest.java file code:

public

class

ExcepTest

{

public

static

void

main

(

String

args

[

]

)

{

int

a

[

]

=

new

int

[

2

]

;

try

{

System

.

out

.

println

(

"

Access element three :

"

a

[

3

]

)

;

}

catch

(

ArrayIndexOutOfBoundsException

e

)

{

System

.

out

.

println

(

"

Exception thrown :

"

e

)

;

}

finally

{

a

[

0

]

=

6

;

System

.

out

.

println

(

"

First element value:

"

a

[

0

]

)

;

System

.

out

.

println

(

"

The finally statement is executed

"

)

;

}

}

}

The compilation and execution results of the above example are as follows:


Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the following:


try-with-resources

After JDK 7, Java added the try-with-resources syntax structure, designed to automatically manage resources, ensuring they are closed promptly after use and avoiding resource leaks.

try-with-resources is an exception handling mechanism that automatically closes resources declared in the try block, without the need to explicitly close them in a finally block.

In a try-with-resources statement, you only need to declare the resource after the try keyword, followed by a block of code. Whether the operations in the block succeed or not, the resource will be automatically closed after the try block finishes execution.

try (resource declaration) {
  // Resources used
} catch (ExceptionType e1) {
  // 异常块
}

In the syntax above, try is used to declare and instantiate the resource, and catch is used to handle all exceptions that may be raised when closing the resource.

**Note:** The try-with-resources statement closes all resources that implement the AutoCloseable interface.

Example

import

java.io.*

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

   

String

line

;

       

try

(

BufferedReader

br

=

new

BufferedReader

(

new

FileReader

(

"test.txt"

)

)

)

{

           

while

(

(

line

=

br.

readLine

(

)

)

!=

null

)

{

               

System

.

out

.

println

(

"Line =>"

line

)

;

           

}

       

}

catch

(

IOException

e

)

{

           

System

.

out

.

println

(

"IOException in try block =>"

e.

getMessage

(

)

)

;

       

}

   

}

}

The output of the above example is:


IOException in try block =>test.txt (No such file or directory)

In the example above, we instantiate a BufferedReader object to read data from the test.txt file.

Declare and instantiate the BufferedReader object in the try-with-resources statement; after execution, the resource is released, without needing to consider whether the try statement completed normally or threw an exception.

If an exception occurs, you can use catch to handle it.

Then look at not using try-with-resources and changing to finally to close the resource; the overall amount of code is much larger and more cumbersome:

Example

import

java.io.*

;

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

BufferedReader

br

=

null

;

       

String

line

;

       

try

{

           

System

.

out

.

println

(

"Entering try block"

)

;

            br

=

new

BufferedReader

(

new

FileReader

(

"test.txt"

)

)

;

           

while

(

(

line

=

br.

readLine

(

)

)

!=

null

)

{

           

System

.

out

.

println

(

"Line =>"

line

)

;

           

}

       

}

catch

(

IOException

e

)

{

           

System

.

out

.

println

(

"IOException in try block =>"

e.

getMessage

(

)

)

;

       

}

finally

{

           

System

.

out

.

println

(

"Entering finally block"

)

;

           

try

{

               

if

(

br

!=

null

)

{

                    br.

close

(

)

;

               

}

           

}

catch

(

IOException

e

)

{

               

System

.

out

.

println

(

"IOException in finally block =>"

e.

getMessage

(

)

)

;

           

}

       

}

   

}

}

The output of the above example is:


Entering try block
IOException in try block =>test.txt (No such file or directory)
Entering finally block

try-with-resources Handling Multiple Resources

Multiple resources can be declared in a try-with-resources statement by separating them with a semicolon (;):

Example

import

java.io.*

;

import

java.util.*

;

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

throws

IOException

{

       

try

(

Scanner scanner

=

new

Scanner

(

new

File

(

"testRead.txt"

)

)

;

           

PrintWriter

writer

=

new

PrintWriter

(

new

File

(

"testWrite.txt"

)

)

)

{

           

while

(

scanner.

hasNext

(

)

)

{

                writer.

print

(

scanner.

nextLine

(

)

)

;

           

}

       

}

   

}

}

The example above uses a Scanner object to read a line from the testRead.txt file and write it to a new testWrite.txt file.

When multiple resources are declared, the try-with-resources statement closes them in reverse order. In this example, the PrintWriter object is closed first, then the Scanner object.

For more information, refer to:

  • try-with-resources:Java try-with-resources Statement
  • Resource management:Java Cleaner Class

  • Declaring Custom Exceptions

    In Java, you can define custom exceptions. When writing your own exception class, keep the following points in mind.

    You can define your own exception class like this:

    class

    MyException

    extends

    Exception

    {

    }

    An exception class created by only extending the Exception class is a checked exception class.

    The InsufficientFundsException class below is a user-defined exception class that extends Exception.

    Like any other class, an exception class contains variables and methods.

    Example

    The following example is a simulation of a bank account, identified by the card number, which can perform deposit and withdrawal operations.

    InsufficientFundsException.java file code:

    //

    File name: InsufficientFundsException.java

    import

    java

    .

    io

    .*;

    //

    Custom exception class, extends the Exception class

    public

    class

    InsufficientFundsException

    extends

    Exception

    {

    //

    The amount here is used to store the money that is lacking when an exception occurs (when the withdrawal exceeds the balance)

    private

    double

    amount

    ;

    public

    InsufficientFundsException

    (

    double

    amount

    )

    {

    this

    .

    amount

    =

    amount

    ;

    }

    public

    double

    getAmount

    (

    )

    {

    return

    amount

    ;

    }

    }

    To demonstrate how to use our custom exception class,

    the CheckingAccount class below contains a withdraw() method that throws an InsufficientFundsException.

    CheckingAccount.java file code:

    //

    File name: CheckingAccount.java

    import

    java

    .

    io

    .*;

    //

    This class simulates a bank account

    public

    class

    CheckingAccount

    {

    //

    balance is the account balance, number is the card number

    private

    double

    balance

    ;

    private

    int

    number

    ;

    public

    CheckingAccount

    (

    int

    number

    )

    {

    this

    .

    number

    =

    number

    ;

    }

    //

    Method: deposit

    public

    void

    deposit

    (

    double

    amount

    )

    {

    balance

    +=

    amount

    ;

    }

    //

    Method: withdraw

    public

    void

    withdraw

    (

    double

    amount

    )

    throws

    InsufficientFundsException

    {

    if

    (

    amount

    <=

    balance

    )

    {

    balance

    -=

    amount

    ;

    }

    else

    {

    double

    needs

    =

    amount

    balance

    ;

    throw

    new

    InsufficientFundsException

    (

    needs

    )

    ;

    }

    }

    //

    Method: return balance

    public

    double

    getBalance

    (

    )

    {

    return

    balance

    ;

    }

    //

    Method: return card number

    public

    int

    getNumber

    (

    )

    {

    return

    number

    ;

    }

    }

    The BankDemo program below demonstrates how to call the deposit() and withdraw() methods of the CheckingAccount class.

    BankDemo.java file code:

    //

    File name: BankDemo.java

    public

    class

    BankDemo

    {

    public

    static

    void

    main

    (

    String

    [

    ]

    args

    )

    {

    CheckingAccount

    c

    =

    new

    CheckingAccount

    (

    101

    )

    ;

    System

    .

    out

    .

    println

    (

    "

    Depositing $500...

    "

    )

    ;

    c

    .

    deposit

    (

    500

    .00

    )

    ;

    try

    {

    System

    .

    out

    .

    println

    (

    "

    \n

    Withdrawing $100...

    "

    )

    ;

    c

    .

    withdraw

    (

    100

    .00

    )

    ;

    System

    .

    out

    .

    println

    (

    "

    \n

    Withdrawing $600...

    "

    )

    ;

    c

    .

    withdraw

    (

    600

    .00

    )

    ;

    }

    catch

    (

    InsufficientFundsException

    e

    )

    {

    System

    .

    out

    .

    println

    (

    "

    Sorry, but you are short $

    "

    e

    .

    getAmount

    (

    )

    )

    ;

    e

    .

    printStackTrace

    (

    )

    ;

    }

    }

    }

    Compile the three files above and run the BankDemo program; the result is as follows:

    
    Depositing $500...
    
    Withdrawing $100...
    
    Withdrawing $600...
    Sorry, but you are short $200.0
    InsufficientFundsException
            at CheckingAccount.withdraw(CheckingAccount.java:25)
            at BankDemo.main(BankDemo.java:13)
    

    General Exceptions

    Two types of exceptions and errors are defined in Java.


    Best Practices for Exception Handling

    Exception handling is an important part of writing robust Java applications. Handling exceptions properly can improve the maintainability and reliability of the program.