try7.java
来自「JAVA 基础例题包含了JAVA常见的问题和常见的习题」· Java 代码 · 共 42 行
JAVA
42 行
class OverflowException extends Exception //自定义异常类
{
public void printMsg()
{
System.out.println("exception: "+this.getMessage());
this.printStackTrace();
System.exit(0);
}
}
public class Try7
{
public void calc(byte k) throws OverflowException //抛出异常
{
byte y=1,i=1;
System.out.print(k+"!=");
for (i=1;i<=k;i++)
{
if(y>Byte.MAX_VALUE/i)
throw new OverflowException();
else
y = (byte)(y * i);
}
System.out.println(y);
}
public void run(byte k) //捕获并处理异常
{
try
{
calc(k);
}
catch(OverflowException e)
{
e.printMsg();
}
}
public static void main (String args[])
{
Try7 a = new Try7();
for (byte i=1;i<10;i++)
a.run(i);
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?