Java中抛出异常并捕获,理解异常处理机制

原创 £神魔★判官ぃ 2024-12-06 16:45 136阅读 0赞

在Java中,异常是程序运行过程中遇到的错误情况。当这些错误发生时,会停止当前方法的执行,并通过向上抛出异常来通知调用者。

异常的处理主要包括两部分:抛出异常和捕获异常。

  1. 抛出异常(Throwing an Exception):
    ```java
    // 自定义异常
    class CustomException extends Exception {
    public CustomException(String message) {
    1. super(message);
    }
    }

public void methodWithException() throws CustomException {
// 引发异常的代码
if (false) {
throw new CustomException(“This is a custom exception.”);
}

  1. // 可选:在方法签名中声明抛出异常
  2. // public void methodWithException(CustomException ex) throws CustomException {
  3. // ...
  4. }

}

  1. 2. 捕获异常(Handling Exceptions):
  2. ```java
  3. public class ExceptionHandlingDemo {
  4. public static void main(String[] args) {
  5. try {
  6. // 调用可能抛出异常的方法
  7. methodWithException();
  8. // 如果方法成功执行,将不会到达这里
  9. System.out.println("Method execution successful.");
  10. } catch (CustomException ex) { // 捕获特定类型的异常
  11. System.out.println("Caught CustomException: " + ex.getMessage());
  12. } catch (Exception anyException) { // 捕获所有未指定类型的异常
  13. System.out.println("Caught any Exception: " + anyException.getMessage());
  14. } finally {
  15. System.out.println("Exiting the program, whether successful or not.");
  16. }
  17. }
  18. // 调用可能抛出异常的方法
  19. public static void methodWithException() throws CustomException {
  20. // ... 方法体代码,这里简化为引发异常的语句
  21. if (false) {
  22. throw new CustomException("This is a custom exception from the method.");
  23. }
  24. }
  25. }

通过上述示例,你可以理解在Java中如何抛出和捕获异常。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读