【问题标题】:How to create exception from another class如何从另一个类创建异常
【发布时间】:2018-03-12 14:40:41
【问题描述】:

我知道如何创建异常,但我想故意“破坏”另一个类。

假设有两个类 X 和 Y。

如果 X 正在运行,我如何创建一个异常导致控制台从 Y 输出异常?

谢谢!

~Java 首选

编辑: 显然 +MarsAtomic 和 +Murat K. 无法正确理解英语。我要求从另一个类抛出异常,而不是正在运行的类。我不明白人们如何在阅读理解水平如此低下的社会中生活。

【问题讨论】:

  • throw new Exception
  • throw new RuntimeException();
  • 显然 +MarsAtomic 和 +Murat K. 无法正确理解英语。我要求从另一个类抛出异常,而不是正在运行的类。我不明白人们如何在阅读理解水平如此低下的社会中生活。

标签: java exception


【解决方案1】:
throw new RuntimeException();

String exceptionMsg = "Error";
throw new RuntimeException(exceptionMsg);

--

public class X
{
   public X()
   {
      Y.CreateException();
      //or
      Y.CreateException("Error");
   }
}

public class Y
{
    public static void createException()
    {
         throw new RuntimeException();
    }

    public static void createException(String msg)
    {
         throw new RuntimeException(msg);
    }
}

【讨论】:

  • 是的,我指的是第三个。谢谢。
【解决方案2】:

假设:

public class thisIsAnException extends Exception{

    private Class source;

    public thisIsAnException(Class source){
        this.source = source;
    }

    public void setSource(Class source) {
        this.source = source;
    }

    @Override
    public String getMessage(){
        return "Oh no, there is an exception in: " + source.getName();
    }
}

public class Y {

    public Y(){
        try {
            X instanceX = new X();
        } catch (thisIsAnException ex) {
            ex.setSource(this.getClass());
            System.err.println(ex.getMessage());
        }
    }

    public static void main(String[] args){
            Y instanceY = new Y();
    }
}

public class X {
    public X () throws thisIsAnException{
        throw new thisIsAnException(this.getClass());
    }
}

这是你的意思吗?

【讨论】:

  • 我就是不明白你在这里做了什么
猜你喜欢
  • 2017-04-07
  • 2016-05-14
  • 2020-05-02
  • 2020-03-26
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
相关资源
最近更新 更多