Home  >  Q&A  >  body text

java中如何让自定义异常像系统的那些异常一样不强制要求处理异常

我在一个类的内部自定义了一个异常,然后在该类的构造方法中根据情况throw这个异常,但是IDE提示我必须要给方法加上throws,同时,在任何其他调用这个方法的地方,都强制要求使用try-catch或者在上级加上throws,我想让他像比如NullPointerException那样,不强制处理异常,而是直接报错终止程序,请问怎么实现?

PHPzPHPz2763 days ago293

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:44:33

    You need to take a good look at the similarities and differences of ExceptionRuntimeException.

    It’s very simple to realize your request

    class MyException extends RuntimeException

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:44:33

    try{
    //需要捕获异常的代码
    } catch (Exception e) {
    System.out.println(e.getMessage();
    }

    If you don’t want to throws, then capture and process them

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 17:44:33

    Then you throw it away and then capture it. After printing the error message, sysrem.exit() exits

    reply
    0
  • Cancelreply