2011-05-16 62 views
0

我有关于检查异常的另一个问题。我试图回答下面的问题。在我的尝试下方是原始问题和代码。如果我是对的,你能否告诉我,或者我可以如何改变我的尝试,使其正确。最诚挚的问候检查成员资格的方法 - 检查异常

public boolean checkMembership(MemberId memberId) 
{ 
    // Firstly the method is tried to see if it works. 
    try { 
     public boolean checkMembership(MemberId memberId) 
    } 
    // If it does not work, then the exception is called 
    catch (InvalidMemberIdException ex){} 
} 

checkMembership方法是Membership类的一部分。它的目的是 用于验证它作为参数传递的memberId,然后尝试在成员列表中找到它 。如果找到memberId,则返回true,否则返回false。

public boolean checkMembership(MemberId memberId) 
{ 
    if (!validate(memberId)) { 
     // An exception must be thrown. 
     … 
    } 
    // Further details of the check membership method are omitted. 
    … 
} 

如果MEMBERID参数checkMembership无效那么 InvalidMemberIdException必须抛出。重写上面显示的 checkMembership方法的一部分,以显示如何完成此操作。请记住,这是一个检查过的异常。您必须包含符合良好文体惯例的详细javadoc 评论。

+1

为什么你在另一个方法声明中有方法声明?而且,为什么抛出一个异常,为什么不把它返回false呢? – bigblind 2011-05-16 18:57:35

回答

0

只需添加一个

throw new InvalidMemberIdException("the id was invalid"); 

和更新的javadoc。

编辑 - 我注意到他们的方法,因为书面递归调用自己(在try catch块内)。你可能不想这样做。另外,在catch块你不想做任何事情('吞下异常'通常是不好的)。在那里写一个日志或其他东西,或者你有意无意的评论。

+0

它正在调用方法减速 - 而不是方法。 它不会编译。 – RonK 2011-05-16 19:00:29

+0

@ronk true。我只是看着评论说抛出异常,并显示如何去做。问题中的代码本身并没有多大意义。 – hvgotcodes 2011-05-16 19:01:46

+0

{ //首先尝试查看方法是否有效。 尝试{ 公共布尔checkMembership(成员Id MEMBERID) } // 如果它不工作,则异常被称为 赶上(InvalidMemberIdException前){}} – bob 2011-05-16 19:04:49