【问题标题】:Java exception throw [duplicate]Java异常抛出[重复]
【发布时间】:2015-09-08 11:13:22
【问题描述】:

如何在Java中抛出异常,尝试了下面的代码,但它引发了编译错误

class Demo{
    public static void main(String args[]) {
        throw new Exception("This is not allowed");
    }
}

【问题讨论】:

标签: java exception


【解决方案1】:

Exception 及其子类(RuntimeException 及其子类除外)如果没有 try-catch 子句或方法声明中的 throws Exception,则无法抛出。

你需要将你的 main 声明为

public static void main(String[] args) throws Exception {

或者用RuntimeException(或其子类)代替Exception

【讨论】:

    【解决方案2】:

    异常处理

    Exception 表示需要更改程序流程的异常事件或情况。

    关键字trycatchthrowthrowsfinally便于修改程序流程。

    简单的想法是Exceptions 从它们出现或被发现的地方抛出,并捕获它们打算被处理的地方。这允许程序执行中的突然跳转,从而实现修改的程序流程。


    平衡

    必须有人可以接住它,否则扔它是不对的。这是您的错误的原因。您没有指定如何或在何处处理异常,并将其抛向空中。


    解决方案

    1. 就地处理

      class Demo{
          public static void main(String args[]) {
              try { // Signifies possibility of exceptional situation
                  throw new Exception("This is not allowed"); // Exception is created
                                                              // and thrown
              } catch (Exception ex) { // Here is how it can be handled
                  // Do operations on ex (treated as method argument or local variable)
              }
          }
      }
      
    2. 强迫别人处理

      class Demo{
          public static void main(String args[]) throws Exception { // Anyone who calls main
                                                                    // will be forced to do
                                                                    // it in a try-catch
                                                                    // clause or be inside
                                                                    // a method which itself
                                                                    // throws Exception
              throw new Exception("This is not allowed");
          }
      }
      

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2012-07-23
      相关资源
      最近更新 更多