使用自定义异常测试compareTo()方法时遇到问题。如何在没有编译错误的情况下抛出自定义异常?
Junit测试代码
@Test
public void compareTo() {
// check equals
assertEquals(0, competitionDressageQualifier.compareTo(competitionDressageQualifier));
try {
Competition c1 = new Competition(competitionDressageQualifier.getEvent(), competitionDressageQualifier.getCompetitionDate(),
competitionDressageQualifier.getJudges(), competitionDressageQualifier.getCompetitionLevel());
assertEquals(0, c1.compareTo(competitionDressageQualifier));
assertEquals(0, competitionDressageQualifier.compareTo(c1));
} catch (OlympicException ex) { //I HAVE THE ERROR HERE Unreachable catch block for OlympicException. This exception is never thrown from the try statement body
// this shouldn't happen
fail();
}
compareTo()的代码,我如何在这里实现try catch?
@Override
public int compareTo(Competition o) //compare properties
{
if(!Objects.equals(this.getCompetitionDate(), o.getCompetitionDate())) //first date
{
return (this.getCompetitionDate().compareTo(o.getCompetitionDate()));
}
else
{
if(!Objects.equals(this.competitionlevel, o.competitionlevel)) //seconds comp level
{
return (this.competitionlevel.compareTo(o.competitionlevel));
}
else
{
if(!Objects.equals(this.getEvent().getEventName(), o.getEvent().getEventName())) //third priority is event name
{
return (this.getEvent().getEventName().compareTo(o.getEvent().getEventName()));
}
}
}
return 0; //if same return 0
}
自定义异常代码:
public class OlympicException extends Exception {
private long serialVersionUID=-1;
public OlympicException()
{
// TODO Auto-generated constructor stub
}
public OlympicException( String s )
{
super( s );
// TODO Auto-generated constructor stub
}
public OlympicException( Throwable cause )
{
super( cause );
// TODO Auto-generated constructor stub
}
public OlympicException( String s, Throwable cause )
{
super( s, cause );
// TODO Auto-generated constructor stub
}
}
无论我尝试什么,我都会得到编译错误,我是否以错误的方式比较了一些东西?
1条答案
按热度按时间7z5jn7bk1#
将其设置为
RuntimeException
:这将修复编译错误,并允许
compareTo()
impl抛出它。