劳动出版社电子课件—Java程序设计基础—Java小管家系统构建 —B04-8329任务10.pptVIP

  • 0
  • 0
  • 约3.94千字
  • 约 23页
  • 2019-05-15 发布于广东
  • 举报

劳动出版社电子课件—Java程序设计基础—Java小管家系统构建 —B04-8329任务10.ppt

课题五 Java处理输入输出及异常处理方法 任务10 处理数据输入的错误 任务引入:一个遗留问题 任务9的输入格式问题 知识准备——了解异常类 知识准备——了解异常类 知识准备——了解异常类 知识准备——异常处理模型 由五个关键字 try、catch、throw、throws 和 finally 处理。 Java 中可用于处理异常的两种方式: 自行处理:可能引发异常的语句封入在 try 块内,而处理异常的相应语句则封入在 catch 块内。 回避异常:在方法声明中包含 throws 子句,通知潜在调用者,如果发生了异常,必须由调用者处理。 课堂演示:try - catch 处理异常 public class ExceptionDemo { ? public static void main(String args[]) { try { int c= calculate(9,0); System.out.println(c); } catch (Exception e) { System.err.println(发生异常: + e.toString()); e.printStackTrace(); } } ? static int calculate(int a, int b) { int c = a/b; return c; } } 课堂练习 完成教材代码10-1 知识准备:多个 catch 块 单个代码片段可能会引起多个错误。 可提供多个 catch 块分别处理各种异常类型。 课堂演示:try – 多catch 处理异常 try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(“请输入第一个数”); int num1=Integer.parseInt(br.readLine()); System.out.println(“请输入第二个数”); int num2=Integer.parseInt(br.readLine()); result = calculate(num1,num2); System.out.println(“结果是”+ result); } catch (NumberFormatException e) { System.err.println(发生异常:必须输入整数); } catch (ArithmetictException e) { System.err.println(发生异常:除数不能为零 ); } catch (IOException e) { System.err.println(发生异常:发生IO异常 ); } 课堂练习 完成教材代码10-2 知识准备:使用 throw 知识准备:使用 throws 如果一个方法可能导致一个异常但不处理它,此时要求在方法声明中包含 throws 子句,通知潜在调用者,如果发生了异常,由调用者处理。 一个throws子句列举了一个方法可能引发的所有异常类型。 这对于除Error或RuntimeException及它们子类以外类型的所有异常是必要的。 课堂演示:使用 throws示例 public static void main(String args[]) { int result=0; try { 。。。。。。 result = calculate(num1,num2); System.out.println(结果是+ result); } catch(Exception ex){ System.out.println(除数为0); } } static int calculate(int a, int b) throws Exception { if(b==0) throw new Exception(); else{ return a/b; } } 课堂练习 完成教材代码10-3 知识准备:finally 块 确保了在出现异常时所有清除工作都将得到处理 与 try 块一起使用 无论是否出现异常,finally块都将运行 课堂练习 完成教材代码10-4 任务分析

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档