我们创建用户定义exception.In类包含一个参数化的构造函数,该构造函数将其参数传递给超类,即Exception类。在这个类之外,我声明了另一个类SimpleThrow.here我输入两个变量x,y的双类型。Z是x,y的除法。如果我把y作为零,它应该把控件抛给catch(ArithmeticException e)块。但是它不抛出除了用户定义的Exception之外的任何catch块,MyclassEx.How我可以让Myclass异常的所有catch块都处于活动状态?
import java.lang.Exception;
import java.util.*;
class MyclassEx extends Exception{
MyclassEx(String msg)
{
super(msg);
System.out.println(msg);
}
}
public class SimpleThrow
{
public static void main(String[] args)
{
try
{
double x=0,y=0,z=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter two numbers:");
x=sc.nextDouble();
y=sc.nextDouble();
z=x/y;
if(z<0.01)
{
**throw new MyclassEx("Number is too small");**
}
}
catch(MyclassEx e)
{
System.out.println("caught exception");
}
catch(ArithmeticException obj)
{
System.out.println("division not possible BY 0");
}
catch(InputMismatchException e2)
{
System.out.println("you have entered wrong key:");
}
finally
{
System.out.println("yoo");
}
}
}
D:\debolina\java\Error_handling>javac SimpleThrow.java
D:\debolina\java\Error_handling>java SimpleThrow
Enter two numbers:45
0
yoo
如果y为0,则z为Double。POSITIVE_INFINITY或Double。NEGATIVE_INFINITY(取决于x符号)。不会引发异常。在您的示例中,z为Double。POSITIVE_INFINITY它大于0.01,因此不会引发MyClassEx异常。