声明异常:throws
抛出异常:throw
public class CircleWithExceptionTest { public static void main(String[] args){ try{ CircleWithException c1 = new CircleWithException(5); CircleWithException c2 = new CircleWithException(-5); CircleWithException c3 = new CircleWithException(0); } catch(IllegalArgumentException ex){ System.out.println(ex); } System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects()); } } class CircleWithException{ private double radius; private static int numberOfObjects = 0; public CircleWithException(){ this(1.0); } public CircleWithException(double newRadius){ setRadius(newRadius); numberOfObjects ++; } public void setRadius(double newRadius) throws IllegalArgumentException{ if(newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException("Radius cannot be negative"); } public double getRadius(){ return radius; } public static int getNumberOfObjects(){ return numberOfObjects; } public double findArea(){ return (radius * radius * 3.14159); } } // 运行结果 /* java.lang.IllegalArgumentException: Radius cannot be negative Number of objects created: 1 */
public class DivideException { public static void main(String[] args){ compute(); } public static void compute(){ try{ divide(5,0); } catch(Exception e){ System.out.println(e.getMessage()); } } public static void compute2() throws Exception{ divide(5,0); } public static void divide(int a, int b) throws Exception{ if(b == 0){ throw new Exception("两数相除,除数不能为0!"); } else{ System.out.println("The result is " + (a/b) ); } } } // 运行结果 /* 两数相除,除数不能为0! */