在 "try" 语句中写什么 - Java - 异常处理?

What to write in "try" statement - Java - Exception Handling?

在 Java 中遇到了另一个问题 - 这次是关于异常处理的 - 我似乎找不到具体的答案。

我有一个 Main Class 和一个 Customer Class 以及 Exception class(但我没有在此处粘贴):

public static void main(String[] args)
{
try
{
    // what can i write in here to make this a valid exception?
    System.out.println("test");
}

catch (InvalidCustomer e)
{
    System.err.println("test");
}

我在 "catch" 语句中遇到错误 - "exception is never thrown in body of corresponding try statement"。

我遇到的问题是 - 我不知道在 try 语句中写什么才能使这项工作正常进行。

public String Customer(String model) throws InvalidCar
{
    String carModel;

    if (validateCar(carModel))
    {
        carModel = model;
    }
    else
    {
        InvalidCar f = new InvalidCar(carModel);
        throw f;
    }

任何帮助将不胜感激 - 我对此非常困惑,也许我只是问错了问题?

您需要在 try 块中调用您的函数 - Customer(string model)。然后可以抛出异常,你就不会再报错了,像这样

public static void main(String[] args)
{
    try
    {
        // what can i write in here to make this a valid exception?
        String model = Customer("myModel");
    }
    catch (InvalidCar e)
    {
        System.err.println("test");
    }
}

那是因为你的 try 块永远不会抛出 InvalidCustomer 并且如果你使用上面的 Customer 函数,那可能只会抛出 InvalidCar 在这种情况下不是 sub-class 共 InvalidCustomer

这可能会像您预期的那样工作:

public String Customer(String model) throws InvalidCustomer{
String carModel;

if (validateCar(carModel))
{
    carModel = model;
}
else
{
    throw new InvalidCustomer();
}

然后,在您的 main() 中:

    try{
    String model = Customer("Illegal Model");
    }catch(InvalidCustomer e){
    System.out.println("gotcha");
    }

您收到错误的原因是 try 块中没有会引发异常的代码。

System.out.println("test"); 不抛出异常。

要使其正常工作,请调用引发 InvalidCustomer 异常的方法。

在 try 块中写入 String customer = Customer("carModel");。还要确保此方法确实抛出 InvalidCustomer。看起来它只是抛出 InvalidCar 异常。 最好将您的方法 (Customer) 重命名为小写 'c'.