Java 异常

try {

    // Protected code

} catch (ExceptionName e1) {

    // Catch block

}
 

Exceptions Methods

Following is the list of important methods available in the Throwable class.

Sr.No.Method & Description
1

public String getMessage()

Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

2

public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

3

public String toString()

Returns the name of the class concatenated with the result of getMessage().

4

public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output stream.

5

public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

6

public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

 

捕获多个异常

try {

    // ...

} catch(ExceptionType1 e1) {

    // ...

} catch(ExceptionType2 e2) {

    // ...

}
try {

    // ...

} catch(ExceptionType1|ExceptionType2 ex) { // since Java 7

    // ...

}

 

Throws / Throw 关键字

  • If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
  • You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.
import java.io.*;


public class ClassName {

    public void withdraw() throws RemoteException, InsufficientFundsException {

        // Method implementation

    }

    // Remainder of class definition

}

 

The finally block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

 

安利一门深度学习课程
扫码下单输优惠码【csdnfxzs】再减5元,比官网还便宜!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanqiliang630

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值