zoukankan      html  css  js  c++  java
  • 实习第一天:try和catch的使用

    package wo;
    public class wowo{
    public static void main(String[] args){
    try{
    // int i = 1/0; 是没有语法错误的,可以编译通过的,
    //int a[3]={2,3,4}; 连编译都通不过,不会输出下面那条语句
    int a[]={0,0,0};
    for(int i=1;i>=-2;i--)
    a[i]=-1; 00
    }
    catch(Exception e){ //在可能出错的地方写上这个语句
    System.out.println("你的程序有错");
    }
    }
    }

    而try则可以保证程序的正常运行下去,比如说:
    try{
    int i = 1/0;
    }catch(Exception e){
    ........
    }
    一个计算的话,如果除数为0,则会报错,如果没有try的话,程序直接崩溃。用try的话,则可以让程序运行下去,并且输出为什么出错!
    try的话,配合log4j使用会对程序的



    1. import java.util.*;  
    2.   
    3. public class Justic {  
    4.     public static void main(String args[])  
    5.     {     
    6.         System.out.println("请输入你想了解的月份");  
    7.         Scanner input = new Scanner(System.in);  
    8.         Calendar c = Calendar.getInstance();  
    9.         int a = c.get(Calendar.YEAR);  
    10.         try{  
    11.             int month = input.nextInt();  
    12.             switch(month){  
    13.             case 1:  
    14.             case 3:  
    15.             case 5:  
    16.             case 7:  
    17.             case 8:  
    18.             case 10:  
    19.             case 12:  
    20.                 System.out.println(month+"月为31天");  
    21.                 break;  
    22.             case 4:  
    23.             case 6:  
    24.             case 9:  
    25.             case 11:  
    26.                 System.out.println(month+"月为30天");  
    27.                 break;  
    28.             case 2:  
    29.                 if(a%4==0 && a%100!=0){  
    30.                     System.out.println(month+"月为29天");  
    31.                     }else{  
    32.                         System.out.println(month+"月为28天");  
    33.                     }  
    34.                 break;  
    35.             default:  
    36.                 System.out.println("你写的个屎啊");  
    37.             }  
    38.         }catch(Exception e){  
    39.             System.out.println("你输入的个P啊");  
    40.         }  
    41.           
    42.           
    43.               
    44.     }  
    45. }  
  • 相关阅读:
    poj 3616 Milking Time
    poj 3176 Cow Bowling
    poj 2229 Sumsets
    poj 2385 Apple Catching
    poj 3280 Cheapest Palindrome
    hdu 1530 Maximum Clique
    hdu 1102 Constructing Roads
    codeforces 592B The Monster and the Squirrel
    CDOJ 1221 Ancient Go
    hdu 1151 Air Raid(二分图最小路径覆盖)
  • 原文地址:https://www.cnblogs.com/cs-lcy/p/6607895.html
Copyright © 2011-2022 走看看