在用throw抛出异常实例时,应该在方法签名中需要使用throws抛出异常,将该异常交给方法调用者来处理。直到main方法,如果依然没有处理,JVM会总之程序,打印异常的跟踪栈信息。
实例代码如下:
-
package BurningT;
-
//import BurningT.AuctionException;
-
class AuctionException extends Exception
-
{
-
public AuctionException()
-
{
-
-
}
-
public AuctionException(String s)
-
{
-
super(s);
-
}
-
}
-
public class AuctionTest{
-
private double initPrice = 30.0;
-
public void auction(String s) throws AuctionException//如果没有throws语句,这不能通过javac编译
-
{
-
double d = 0.0;
-
try
-
{
-
d = Double.parseDouble(s);
-
} catch (Exception e)
-
{
-
e.printStackTrace();
-
throw new AuctionException("s is not a String");
-
}
-
if (d < initPrice)
-
{
-
throw new AuctionException("The price is not resonable");
-
}
-
initPrice = d;
-
}
-
public static void main(String[] args)
-
{
-
AuctionTest at = new AuctionTest();
-
try
-
{
-
at.auction("str");
-
}
-
catch(AuctionException ae)
-
{
-
System.err.println(ae.getMessage());
-
}
-
}
-
}
没有throws语句使用javac编译结果如下:
E:\HelloFile\javaTest>javac -d . AuctionTest.java
AuctionTest.java:25: 错误: 未报告的异常错误AuctionException; 必须对其进行捕获或声明以便抛出
throw new AuctionException("s is not a String");
^
AuctionTest.java:29: 错误: 未报告的异常错误AuctionException; 必须对其进行捕获或声明以便抛出
throw new AuctionException("The price is not resonable");
^
AuctionTest.java:40: 错误: 在相应的 try 语句主体中不能抛出异常错误AuctionException
catch(AuctionException ae)
^
3 个错误
正确使用throws后:运行结果如下:
E:\HelloFile\javaTest>java BurningT.AuctionTest
java.lang.NumberFormatException: For input string: "str"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at BurningT.AuctionTest.auction(AuctionTest.java:21)
at BurningT.AuctionTest.main(AuctionTest.java:38)
s is not a String
搞了一个多小时才发现忘写了一个throws AuctionException
阅读(3223) | 评论(0) | 转发(0) |