如果我没看错的话,你的错误很明显。在你上边的code 里边,MyException 从来没有被抛出过,那么当然你永远也不会捕捉到他。
class MyException extends Exception
{
//我写的有问题!
MyException() { super(); }
MyException(String s) { super(s); }
};class whilerror
{
public static void main(String[] args)
{
try
{
double d = 0.0;
while ( d != 5.0 )
{
//Error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//死循环!!!!!!!
d = d + (1.0 /3.0);
System.out.println( d );
}
}
catch (MyException e)
{
System.out.println( e.getMessage() );
} }
}
class MyException extends Exception
{
//我写的有问题!
MyException() { super(); }
MyException(String s) { super(s); }
};class whilerror
{
public static void main(String[] args)
{
try
{
double d = 0.0;
while ( d != 5.0 )
{
//Error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//死循环!!!!!!!
d = d + (1.0 /3.0);
System.out.println( d );
}
}
catch (MyException e)
{
System.out.println( e.getMessage() );
} }
}
语法格式为:throw 异常类名;
要加上异常抛出的条件
这样应该就可以了
class MyException extends Exception
{
//我写的有问题!
MyException() { super(); }
MyException(String s) { super(s); }
};class whilerror
{
public static void main(String[] args)
{
try
{
double d = 0.0;
while ( d != 5.0 )
{
//Error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//死循环!!!!!!!
d = d + (1.0 /3.0);
throw new MyException("死循环");
System.out.println( d );
}
}
catch (MyException e)
{
System.out.println( e.getMessage() );
} }
}
throw new MyException("死循环");
此语句前面应加上一个条件判断,如:
if(d>5.0)
throw new MyException("死循环");