zoukankan      html  css  js  c++  java
  • java异常处理

    1. 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:

    ²  在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;

    ²  在catch语句块中,捕获被0除所产生的异常,并输出异常信息;

    ²  在finally语句块中,输出一条语句。

     1 package aaa;
     2 import java.rmi.MarshalException;
     3 import java.util.*;
     4 
     5 public class ExceptionTest {
     6     static int avg(int a,int b) throws MarshalException{
     7         if (b==0){
     8             throw new MarshalException("除数不能为0");
     9         }
    10         return a/b;
    11         
    12     }
    13 
    14     public static void main(String[] args) {
    15 
    16         
    17         try{
    18             Scanner sc = new Scanner (System.in);
    19             int a,b,c;
    20             System.out.println("请输入除数与被除数:");
    21             a = sc.nextInt();
    22             b = sc.nextInt();
    23             int result = avg (a,b);
    24             c = a/b;
    25             System.out.println("计算结果为:"+c);
    26             
    27         }
    28         catch(MarshalException e){
    29             System.out.println(e.getMessage());
    30         }
    31         finally{
    32             System.out.println("运行结束。");
    33         }
    34 
    35     }
    36 
    37 }

    1. 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。

     1 package bbb;
     2 import java.rmi.MarshalException;
     3 import java.util.*;
     4 public class Area {
     5     public static void main(String[] args) {
     6         final double PI=3.14159;
     7         
     8         try{
     9             Scanner sc = new Scanner (System.in);
    10             double r,s;
    11             System.out.println("请输入园的半径");
    12             r = sc.nextInt();
    13             s = PI*r*r;
    14             System.out.println("计算结果为:"+s);
    15             
    16         }
    17         catch(Exception e){
    18             System.out.println("输入数据格式不正确");
    19         }
    20         finally{
    21             System.out.println("运行结束。");
    22         }
    23         
    24         
    25 
    26 
    27     }
    28 
    29 }
  • 相关阅读:
    POJ3352 Road Construction (双连通分量)
    强连通分量(模板)
    图基本概念
    Air Raid(最小路径覆盖)
    Machine Schedule(最小覆盖)
    hdoj 1564 Play a game
    nyoj 483 Nightmare【bfs+优先队列】
    hdoj 1083 Courses【匈牙利算法】
    hdoj 2036 改革春风吹满地
    nyoj 353 3D dungeon
  • 原文地址:https://www.cnblogs.com/sxcxfl/p/10843538.html
Copyright © 2011-2022 走看看