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

    >>>>>>>>>>>>>>>>>>>>
    作用:防止程序因“异常”而停止运行
     
     
    try{
           可能会发生错误的语句(被保护的代码块)    }
    catch(){
           输出语句(处理方式)    }
        
                   【可有0~多个catch语句】
    finally{
    不管异常是否发生都要执行的代码块    } 
    学习时间:2016.11.19
     >>>>>>>>>>>>>>>>>>>>
    代码实例:
     1 package a;
     2 public class a {
     3     public static void main(String[] args) {
     4         String[] F={"wk","ym","6"};
     5         try {
     6         for(int i=0;i<5;i++){
     7             System.out.println("我的朋友是:"+F[i]);
     8         }
     9         }
    10         catch(ArrayIndexOutOfBoundsException e){
    11             System.out.println("如果出异常,则输出此语句");
    12         }
    13         System.out.println("你好啊,我的朋友");
    14     }
    15 }
    16 
    17 /*
    18  * try{循环体}
    19  * catch(){输出语句}
    20  * 
    21  */

    >>>>>>>>>>>>>>>>>>>>

     学习时间:2016.11.29晚

    二代代码详情:

     1 package lianxi;
     2 
     3 import java.util.Scanner;
     4 /*下面我需要一个数字,只能是正整数!
     5  * 要求:输入错误可以无限次重新输入!并提示
     6  *         考虑到只要正整数,能处理0、负数、非数字等输入。
     7  *         健壮性高!
     8  * */
     9 public class trydemo {
    10     static Scanner input = new Scanner(System.in);
    11     public static void main(String[] args) {
    12         int number=0;
    13         
    14         while(true){
    15             System.out.print("请输入正数:");
    16         try{
    17             //把接收的字符强制转换成int整型
    18          number = Integer.parseInt(input.next());
    19          if(number>0){break;}
    20          //解决输入负数的情况
    21          else{System.out.println("1输入的值不符合要求!请重新输入一个正整数:");}
    22         }catch(Exception E)//解决输入非数字的情况
    23         {System.out.println("2输入的值不符合要求!请重新输入一个正整数:");}
    24         }
    25         System.out.println(number);
    26     }
    27 }

    效果如图:

  • 相关阅读:
    LeetCode "Jump Game"
    LeetCode "Pow(x,n)"
    LeetCode "Reverse Linked List II"
    LeetCode "Unique Binary Search Trees II"
    LeetCode "Combination Sum II"
    LeetCode "Divide Two Integers"
    LeetCode "First Missing Positive"
    LeetCode "Clone Graph"
    LeetCode "Decode Ways"
    LeetCode "Combinations"
  • 原文地址:https://www.cnblogs.com/xuehx/p/6113263.html
Copyright © 2011-2022 走看看