如何在Java中定义自定义异常类,最简单的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3776327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define custom exception class in Java, the easiest way?
提问by yegor256
I'm trying to define my own exception class the easiest way, and this is what I'm getting:
我正在尝试以最简单的方式定义自己的异常类,这就是我得到的:
public class MyException extends Exception {}
public class Foo {
public bar() throws MyException {
throw new MyException("try again please");
}
}
This is what Java compiler says:
这是 Java 编译器所说的:
cannot find symbol: constructor MyException(java.lang.String)
I had a feeling that this constructor has to be inherited from java.lang.Exception
, isn't it?
我有一种感觉,这个构造函数必须继承自java.lang.Exception
,不是吗?
采纳答案by djna
No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message)
in your constructor to invoke your parent constructor. For example, like this:
不,您不会“继承”非默认构造函数,您需要在类中定义采用 String 的构造函数。通常,您super(message)
在构造函数中使用来调用父构造函数。例如,像这样:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
回答by vulkanino
If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).
如果从 Exception 继承,则必须提供一个将 String 作为参数的构造函数(它将包含错误消息)。
回答by nanda
A typical custom exception I'd define is something like this:
我定义的一个典型的自定义异常是这样的:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable throwable) {
super(message, throwable);
}
}
I even create a template using Eclipse so I don't have to write all the stuff over and over again.
我什至使用 Eclipse 创建了一个模板,所以我不必一遍又一遍地编写所有的东西。
回答by Isaq
Reason for this is explained in the Inheritancearticle of the Java Platform which says:
原因在 Java 平台的继承文章中进行了解释,其中说:
"A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass."
“子类从其超类继承所有成员(字段、方法和嵌套类)。构造函数不是成员,因此它们不会被子类继承,但可以从子类调用超类的构造函数。”
回答by Deepak Pakhale
Exception class has two constructors
异常类有两个构造函数
public Exception()
-- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.public Exception(String s)
-- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.
public Exception()
-- 这将构造一个没有任何附加信息的异常。异常的性质通常是从类名中推断出来的。public Exception(String s)
-- 使用指定的错误消息构造异常。详细消息是描述此特定异常的错误条件的字符串。
回答by Deepak Pakhale
package customExceptions;
public class MyException extends Exception{
public MyException(String exc)
{
super(exc);
}
public String getMessage()
{
return super.getMessage();
}
}
import customExceptions.MyException;
public class UseCustomException {
MyException newExc=new MyException("This is a custom exception");
public UseCustomException() throws MyException
{
System.out.println("Hello Back Again with custom exception");
throw newExc;
}
public static void main(String args[])
{
try
{
UseCustomException use=new UseCustomException();
}
catch(MyException myEx)
{
System.out.println("This is my custom exception:" + myEx.getMessage());
}
}
}
回答by Kevin Brey
If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception
and check "Constructors from superclass" and it will generate the following:
如果您在 Eclipse 中使用新类对话框,您只需将 Superclass 字段设置为java.lang.Exception
并选中“Constructors from superclass”,它将生成以下内容:
package com.example.exception;
public class MyException extends Exception {
public MyException() {
// TODO Auto-generated constructor stub
}
public MyException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public MyException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
In response to the question below about not calling super()
in the defualt constructor, Oracle has this to say:
为了回答下面关于不调用super()
默认构造函数的问题,Oracle 有这样的说法:
Note:If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
注意:如果构造函数没有显式调用超类构造函数,Java 编译器会自动插入对超类的无参数构造函数的调用。
回答by Lorne K
and don't forget the easiest way to throw an exception (you don't need to create a class)
并且不要忘记抛出异常的最简单方法(您不需要创建类)
if (rgb > MAX) throw new RuntimeException("max color exceeded");