你如何在java中返回方法的结果?

Lia*_*yan 0 java return

这是关于多个catch块的问题的后续如何处理返回对象和处理错误

我的更新代码如下,但是我得到一个错误,我的draw()方法必须返回一个int,有没有办法让编译器识别endOfDeck()将返回一个int,从而满足返回要求?(参见"return endOfDeck())

有任何更聪明的方法来实现这一目标

import java.util.ArrayList;
import java.util.ListIterator;
/**
 * @author L
 *
*/
public abstract class Deck 
{

private ArrayList<Card> cards;
private ListIterator<Card> deckPosition = cards.listIterator();
private Card lastDrawn;
/**
 * 
 */
public Deck() 
{   
}

public int draw()
{

    try
    {
        if(deckPosition.hasNext())
        {
            lastDrawn = deckPosition.next();
            return 1;
        }
        else if(cards.isEmpty())
        {
            throw new EmptyDeckException();
        }
        else
        {
            throw new EndOfDeckException();
        }
    }

    catch(EmptyDeckException e)
    {
        emptyDeck();
        return 0;
    }
    catch(EndOfDeckException e)
    {
        return endOfDeck();

    }
    catch(Exception e)
    {
        System.out.println("Exception when drawing a card, check try/catch block in draw() method of Card");
        e.printStackTrace();
    }

}

public abstract int endOfDeck();
public abstract void emptyDeck();

}
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 6

您的最后一个catch区块没有任何退货声明: -

catch(Exception e)
    {
        System.out.println("Exception when drawing a card, check try/catch block in draw() method of Card");
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

因此,如果执行了catch块,则您的方法不会返回任何值.可能是您可以返回表示异常的任何整数,或者将异常包装在a中RuntimeException并重新抛出它.


但是,您的代码似乎有些问题.你不必要地抛出异常.无论你在catch街区做什么,你都可以直接在你的if-else街区里做.

因此,您可以将代码修改为: -

    try {
        if(deckPosition.hasNext())
        {
            lastDrawn = deckPosition.next();
            return 1;
        }
        else if(cards.isEmpty())
        {
            emptyDeck();
            return 0;
        }
        else
        {
            // throw new EndOfDeckException();  // Don't throw it
            return endOfDeck();
        }

    } catch(Exception e) {
        /** Also, if possible, replace this catch block with the one catching
            more specific exception than all the `Exceptions` **/
        System.out.println("Exception when drawing a card, check try/catch block in draw() method of Card");
        throw new RuntimeException("Exception drawing a card");
    }
Run Code Online (Sandbox Code Playgroud)