标签: custom-exceptions

如果是循环,则抛出自定义异常

public class StringArray {
    private String strArr[];

    public StringArray(int capacity) {
       strArr = new String [capacity];
    }

    public int indexOf(String s) throws StringNotFoundException {
        for(int i=0;i<strArr.length ;++i) {
            if (strArr[i].equals(s)) {
                return i;
            } else {
                throw new StringNotFoundException();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是返回我正在寻找的字符串的索引,如果它在数组中,否则抛出异常.

然而Eclipse说我必须返回一个int.

那么我应该将返回类型更改为void还是有其他选项?

StringNotFoundException是我编写的自定义异常.

java arrays for-loop exception custom-exceptions

0
推荐指数
1
解决办法
247
查看次数

Java异常:异常是否应在其中包含其消息或将其作为参数

每当我需要定义一个自定义异常时,如果它的消息不会根据上下文而改变,我将消息放在该异常中.像这样:

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException() {
        super("User with given name is not found!");
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是这个:

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,每次抛出此异常时我都不需要提供消息,我知道消息在每个地方都应该是相同的.

你觉得我的方法有问题吗?你更喜欢哪一个,为什么?

java exception-handling exception conventions custom-exceptions

0
推荐指数
1
解决办法
391
查看次数

我无法让我的方法抛出自定义异常

我有一个类EmployWorker和我为学校项目创建的超类Employee.我们应该在本周为它设置例外,并且在尝试创建其中一个时我一直收到错误.这是我的代码:

在ProductionWorker中:

   public String toString() throws InvalidShift{
      DecimalFormat dollar = new DecimalFormat("$#,##0.00");
      String str = super.toString();

      str += "The employee's pay rate is " + dollar.format(getPayRate()) +"\n";
      str += "The employee works the " + getShift() + " shift";
      return str;
   }
Run Code Online (Sandbox Code Playgroud)

super.toString类:

   public String toString() throws InvalidShift{
      String str = "The employee's name is " + getEmployeeName() + ".\n";
      if (employeeNumber.equals("")){
         str += "The employee's ID number is invalid.\n";
      }else{
         str += "The Employee's ID number is " + …
Run Code Online (Sandbox Code Playgroud)

java methods exception custom-exceptions superclass

0
推荐指数
1
解决办法
965
查看次数

Python - 实现自定义异常

我有一个项目需要运行,不知道如何实现自定义异常.它主要做复杂的科学功能,含糊不清.

如果没有设置某些内容,通常会引发异常.我已经把它作为runnables的一个开始例子.

    # Define a class inherit from an exception type
class CustomError(Exception):
    def __init__(self, arg):
        # Set some exception infomation
        self.msg = arg

try:
    # Raise an exception with argument
    raise CustomError('This is a CustomError')
except CustomError, arg:

# Catch the custom exception
print 'Error: ', arg.msg
Run Code Online (Sandbox Code Playgroud)

我不知道这是如何工作的,或者我是如何实现我的代码的.它不是很明确.

了解需要创建的基本异常.

在一个功能:

if self.humidities is None:
        print "ERROR: Humidities have not been set..."
        return
Run Code Online (Sandbox Code Playgroud)

显然,这需要引发/抛出异常.

python error-handling custom-exceptions

0
推荐指数
1
解决办法
6864
查看次数

创建自己的异常并在C#中使用它

我试图了解如何以正确的方式使用自定义异常.

我已经多次使用过try/catch但是从来没有说过何时使用自己的类关闭异常.我已经阅读并观看了许多教程,但我无法理解这一点.

这是我的CustomException班级:

[Serializable]
    class CustomException : FormatException
    {
        /// <summary>
        /// Just create the exception
        /// </summary>
        public CustomException()
        : base() {
        }
        /// <summary>
        /// Create the exception with description
        /// </summary>
        /// <param name="message">Exception description</param>
        public CustomException(String message)
        : base(message) {
        }
        /// <summary>
        /// Create the exception with description and inner cause
        /// </summary>
        /// <param name="message">Exception description</param>
        /// <param name="innerException">Exception inner cause</param>
        public CustomException(String message, Exception innerException)
        {
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我尝试使用它的地方:

    /// <summary> …
Run Code Online (Sandbox Code Playgroud)

c# exception custom-exceptions

0
推荐指数
1
解决办法
695
查看次数

调用自定义异常时的TypeError

我正在尝试在使用不正确的输入创建对象时抛出自定义错误,但在尝试引发异常时遇到此错误.

TypeError: exceptions must derive from BaseException
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的相关代码

def UnitError(Exception):
    pass

def ValueError(Exception):
    pass

class Temperature():

    def __init__(self, temp = 0.0, unit = 'C'):

        if type(temp) != int:
            raise ValueError('TEST') #ERROR occurs here
        else:
            self.t = float(temp)

        self.u = unit.upper()
Run Code Online (Sandbox Code Playgroud)

我以前在提出自定义异常时从未遇到过这个错误,有人可以解释这里发生了什么,以及我如何解决它?

python custom-exceptions python-3.x

0
推荐指数
1
解决办法
329
查看次数