Ja15-08第9章异常处理精选.ppt

* 抛出异常 使用throw语句抛出的异常对象的语法格式为: 在一个方法内使用throw抛出异常对象,若该方法内部没有用try-catch对这个抛出的异常进行处理,则此方法应声明抛出异常,由其调用着处理。 异常抛出点后的代码在抛出异常后不再执行,也可以说异常的抛出终止了代码段的执行。 任何从Throwable派生的类都可以用throw语句抛出,抛出异常用来表明程序遇到的错误无法正常执行而需要异常处理 throw 由异常类所产生的对象; * class JavaThrow { public static void main(String args[]) { } } try { throw new ArithmeticException(); }catch(ArithmeticException ae){ System.out.println(ae); } try { throw new ArrayIndexOutOfBoundsException(); }catch(ArrayIndexOutOfBoundsException ai){ System.out.println(ai); } try { throw new StringIndexOutOfBoundsException(); }catch(StringIndexOutOfBoundsException si){ System.out.println(si); } * import java.util.Scanner; public class Dance1{ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println(Enter number of male dancers:); int men = keyboard.nextInt(); System.out.println(Enter number of female dancers: ); int women = keyboard.nextInt(); if (men == 0 women == 0) { System.out.println(没有一个学员.); System.exit(0); } else if (men == 0) { System.out.println(没有男学员.); System.exit(0); } else if (women == 0) { System.out.println(没有女学员.); System.exit(0); } System.out.println(有学员,可以开课.); } } 没有使用异常 的 例子 * import java.util.Scanner; public class Dance2 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println(Enter number of male dancers:); int men = keyboard.nextInt(); System.out.println(Enter number of female dancers:); int women = keyboard.nextInt(); try{ if (men == 0 women == 0) throw new Exception(没有一个学员.); else if (men == 0) throw new Exception(没有男学员.); else if (women == 0) throw new Ex

文档评论(0)

1亿VIP精品文档

相关文档