簡體   English   中英

在“ try”語句中寫什么-Java-異常處理?

[英]What to write in “try” statement - Java - Exception Handling?

在Java中還有另一個問題-這次是關於異常處理的-我似乎找不到具體的答案。

我有一個Main類和一個Customer類以及Exception類(但是我​​沒有在這里粘貼它):

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”語句中遇到錯誤-“相應的try語句的主體中永遠不會拋出異常”。

我遇到的問題是-我不知道要在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 ,在這種情況下, InvalidCustomer不是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異常的方法。

寫入String customer = Customer("carModel"); 在try塊中。 還要確保此方法確實會拋出InvalidCustomer。 看起來它只是拋出InvalidCar異常。 並且最好將您的方法(客戶)重命名為小寫的“ c”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM