在Java中抛出自定义异常 [英] Throwing custom exceptions in Java

查看:1585
本文介绍了在Java中抛出自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我需要用尝试 / catch 来包装我抛出的自定义异常,同时尝试抛出它们,但是我不必为通用异常这样做吗?就像在示例中一样,我的异常子类:

Why do I need to wrap my thrown custom exceptions with try/catch whilst trying to throw them, but I don't have to do that for generic exceptions? Like in the example, my Exception subclass :

public class MyException extends Exception {
    public MyException(String msg) {
        super(msg);
    }
}

抛出异常:

public class Exe {

    private static void testex(String test) {
        if (null!=test) {
            throw new UnsupportedAddressTypeException();
        } else {//Removing try/catch block results in compile failure
          try {
            throw new MyException("message");
          } catch (MyException e) {
            e.printStackTrace();
          }
        }
    }
}


推荐答案

UnsupportedAddressTypeException是RuntimeException的子类,来自JavaDoc:

UnsupportedAddressTypeException is a subclass of RuntimeException, and from the JavaDoc:


RuntimeException是这些异常的超类在Java虚拟机的正常操作期间可以抛出。

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

在throws子句中声明可能在其期间抛出的RuntimeException的任何子类都不需要方法。执行该方法但未捕获。

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

这篇关于在Java中抛出自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆