1. 程式人生 > 其它 >10-常見API&異常

10-常見API&異常

1.常見API

1.1Math

  • Math概述

    Math包含執行基本數字運算的方法

  • Math中方法的呼叫方式

    Math類中無構造方法,但內部的方法都是靜態的,則可以通過 類名**.**進行呼叫

  • Math類的常用方法

    方法名說明
    public static int abs(int a)返回引數的絕對值
    public static double ceil(double a)返回大於或等於引數的最小double值,等於一個整 數
    public static double floor(double a)返回小於或等於引數的最大double值,等於一個整 數
    public static int round(float a)按照四捨五入返回最接近引數的int
    public static int max(int a,int b)返回兩個int值中的較大值
    public static int min(int a,int b)返回兩個int值中的較小值
    public static double pow (double a,double b)返回a的b次冪的值
    public static double random()返回值為double的正值,[0.0,1.0)

1.2System

  • System類的常用方法
方法名說明
public static void exit(int status)終止當前執行的 Java 虛擬機器,非零表示異常終止
public static long currentTimeMillis()返回當前時間(以毫秒為單位)
public static void arraycopy(<Object src, int srcPos, Object dest, int destPos, intlength)複製陣列
  • 示例程式碼
public class Demo01 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 1; i <
10000; i++) { System.out.println(i); } long end = System.currentTimeMillis(); System.out.println("一共花了:" +(end - start) + "毫秒"); //static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) // 將指定源陣列中的陣列從指定位置複製到目標陣列的指定位置。 int[] arr1 = {1,2,3,4,5}; int[] arr2 =new int[10]; System.arraycopy(arr1,0,arr2,0,arr1.length); for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i]); } System.out.println("---------"); //把第一個陣列的最後倆個數據,copy到arr2的最後的倆個位置 System.arraycopy(arr1,3,arr2,8,2); for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i]); } } }

1.3Object類的toString方法

  • Object類概述
    • Object 是類層次結構的根,每個類都可以將 Object 作為超類。所有類都直接或者間接的繼承自該類,換句話說,該類所具備的方法,所有類都會有一份
  • 檢視方法原始碼的方式
    • 選中方法,按下Ctrl + B
  • 重寫toString方法的方式
    • Alt + Insert 選擇toString
    • 在類的空白區域,右鍵 -> Generate -> 選擇toString
  • toString方法的作用:
    • 以良好的格式,更方便的展示物件中的屬性值

1.4Object類的equals方法

  • equals方法的作用
    • 用於物件之間的比較,返回true和false的結果
    • 舉例:s1.equals(s2); s1和s2是兩個物件
  • 重寫equals方法的場景
    • 不希望比較物件的地址值,想要結合物件屬性進行比較的時候
  • 子類沒有重寫equals方法:比較的是地址值,等價於“==”
  • 子類重寫了equals方法:比較的是屬性值
  • 注意:在API中有一些類,本身就複寫了toString和equals方法

1.5Objects類

​ Objects類是JDK7之後才有的工具類,可以用來判斷物件是否為null等操作

1.static boolean nonNull(Object obj) 
	返回 true如果提供的參考是非 null否則返回 false
	
2.static boolean isNull(Object obj)
	返回 true如果提供的引用是 null否則返回 false
	
3.static String toString(Object o) 
	返回非 null引數呼叫 toString的結果和 null引數的 "null"的 null
	
4.static String toString(Object o, String nullDefault) 
	如果第一個引數不是 null ,則返回第一個引數上呼叫 toString的結果,否則返回第二個引數。

1.6氣泡排序原理

  • 氣泡排序概述
    • 一種排序的方式,對要進行排序的資料中相鄰的資料進行兩兩比較,將較大的資料放在後面,依次對所有的資料進行操作,直至所有資料按要求完成排序
  • 如果有n個數據進行排序,總共需要比較n-1次
  • 每一次比較完畢,下一次的比較就會少一個數據參與
  • 程式碼實現
public class test03 {
    public static void main(String[] args) {
        int[] arr = {11, 22, 34, 21, 23};
        System.out.println("排序前:" + arrayToString(arr));
        bubbleSort(arr);
        System.out.println("排序後:" + arrayToString(arr));
    }
    //氣泡排序
    public static void bubbleSort(int[] arr) {
        if(arr==null || arr.length < 2 ){
            return;
        }
        // 這裡減1,是控制每輪比較的次數
        for (int i = 0; i < arr.length - 1; i++) {
            // 1是為了避免索引越界,x是為了調高比較效率
            for (int j = 0; j < arr.length - i -1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    //拼接
    public static String arrayToString(int[] arr) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(",");
            }
        }
        sb.append("]");
        String s = sb.toString();
        return s;
    }
}

1.7二分查詢

  • 二分查詢要求陣列的元素必須要是從小到大的順序,否則做不了二分查詢

    思路:
    1.定義開始索引和結束索引
    int start=0;
    int end=array.length-1;
    2.計算中間的索引
    int mid=(start+end)/2;
    3.讓中間元素和目標元素進行比較
    如果:array[mid]>key,end=mid-1
    如果:array[mid]<key,start=mid+1
    如果:array[mid]==key,mid就是最終的結果
    如果所有的元素都沒有相等,就沒有找到,返回-1
    
  • 程式碼實現

    public class ArrayDemo01 {
        public static void main(String[] args) {
            int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int number = 5;
            int i = Arrays.binarySearch(arr, 5);
            System.out.println("Arrays.binarySearch:" + i);
            int index = getIndex(arr, number);
            System.out.println("index:" + index);
        }
    
        public static int getIndex(int[] arr, int number) {
            int start = 0;
            int end = arr.length - 1;
            while (start < end) {
                int mid = (start + end) / 2;
                if (arr[mid] > number) {
                    //表示要找的元素在mid的左邊
                    end = mid - 1;
                }
                if (arr[mid] < number) {
                    //表示要找的元素在mid的右邊
                    start = mid + 1;
                } else if (arr[mid] == number) {
                    return mid;
                }
            }
            return -1;
        }
    }
    

1.8快速排序

  • 程式碼實現
public class ArrayDemo05 {
    public static void main(String[] args) {
        int[] arr = {6, 2, 1, 7, 9, 5, 4, 3, 10, 8};
        quickSort(arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr, int left, int right) {
        if (left>right){
            return;
        }
        //記錄最開始的索引位置
        int left0 = left;
        int right0 = right;
        //確定基準數
        int baseNumber =arr[left0];
        while (left<right) {
            while (arr[right] >=baseNumber && left < right) {
                right--;
            }
            while (arr[left] <= baseNumber && left < right) {
                left++;
            }
            //交換資料
            int temp = arr[left];
            arr[left]=arr[right];
            arr[right]=temp;
        }
        //交換基準數
        arr[left0]=arr[left];
        arr[left] = baseNumber;
        //遞迴
        quickSort(arr,left0,left-1);
        quickSort(arr,right+1,right0);
    }
}

1.9Arrays

  • Arrays的常用方法

    方法名說明
    public static int binarySearch(int[] a, int key)使用二分查詢法對查詢陣列中的元素;如果沒有找到,返回一個負數
    public static String toString(int[] a)返回指定陣列的內容的字串表示形式
    public static void sort(int[] a)按照數字順序排列指定的陣列

2.BigDecimal類

  • BigDecimal可以對資料進行精確的運算,需要用它提供的方法對資料進行運算

  • BigDecimal的常用方法

    方法名說明
    public BigDecimal add(BigDecimal augend)加法運算
    public BigDecimal subtract(BigDecimal subtrahend)減法運算
    public BigDecimal multiply(BigDecimal multiplicand)乘法運算
    public BigDecimal divide(BigDecimal divisor)除法運算
  • public BigDecimal divide(BigDecimal divisor, int scale,int roundingMode)
    	除法運算,可以保留指定的小數位
    	引數解釋:
    		BigDecimal divisor:參與運算的除數
    		int scale:保留的位數
    		int roundingMode: 舍入模式
    			BigDecimal.ROUND_UP: 進一法
    			BigDecimal.ROUND_Floor: 去尾法
    			BigDecimal.ROUND_HALF_UP: 四捨五入
    
  • 注意:

    • 演示四則運算:參與要運算的資料,都需要封裝尾BigDecimal物件
    • 進行精確運算的時候,用字串的構造
  • 用BigDecimal類對陣列元素求和

    public class Demo03 {
        public static void main(String[] args) {
            int[] arr = {11, 22, 33, 44, 55};
            BigDecimal sum = new BigDecimal("0");
            for (int i = 0; i < arr.length; i++) {
                BigDecimal bd1 = new BigDecimal(arr[i] + "");
                sum = sum.add(bd1);
            }
            System.out.println(sum);
        }
    }
    

2.包裝類

2.1基本型別包裝類

  • 基本型別包裝類的作用

    將基本資料型別封裝成物件的好處在於可以在物件中定義更多的功能方法操作該資料
    常用的操作之一:用於基本資料型別與字串之間的轉換

  • 基本型別對應的包裝類

    基本資料型別包裝類
    byteByte
    shortShort
    intInteger
    longLong
    floatFloat
    doubleDouble
    charCharacter
    booleanBoolean

2.2Integer類

  • Integer類概述

    包裝一個物件的原始型別int值

  • Integer類的構造方法

    方法名說明
    public Integer(int value)根據 int 值建立 Integer 物件(過時)
    public Integer(String s)根據 String 值建立 Integer 物件(過時)
    public static Integer valueOf(int i)返回表示指定的 int 值的 Integer 例項
    public static Integer valueOf(String s)返回一個儲存指定值的 Integer 物件 String

2.3int型別和String型別的相互轉換

  • int轉換String

    • 轉換方式
      • 方式一:直接在數字後面加空字串
      • 方式二:通過String類靜態方法valueOf()
    • 示例程式碼
    public class IntegerDemo02 {
        public static void main(String[] args) {
            //方式一
            //int-String
            int number = 100;
            String s = number + "";
            System.out.println(s);
            System.out.println("---------");
            //方式二
            public static String valueOf(int i)
            String s1 = String.valueOf(number);
            System.out.println(s1);
        }
    }
    
  • String轉換為int

    • 轉換方式
      • 方式一:先將字串數字型別轉成Integer,在呼叫valuseOf()方法
      • 方式二:通過Integer靜態方法parseInt()進行轉換
    • 示例程式碼
    public class IntegerDemo03 {
        public static void main(String[] args) {
            //方式一
            //String --- Integer --- int
            String s = "100";
            Integer integer = Integer.valueOf(s);
            int i = integer.intValue();
            System.out.println(i);
            System.out.println("---------");
            //方式2
            //public static int parseInt(String s)
            int parseInt = integer.parseInt(s);
            System.out.println(parseInt);
        }
    }
    

2.4字串資料排序案例

  • 需求:有一個字串:“91 27 46 38 50”,請寫程式實現最終輸出結果是:“27 38 46 50 91”

  • 程式碼實現

    public class IntegerDemo04 {
        public static void main(String[] args) {
            //定義一個字串
            String s = "91 27 46 38 50";
            //得到字串中的每一個字元資料
            //public string[] split(String regex)
            String[] strArray = s.split(" ");
            //定義一個int型別的陣列,把string型別陣列的每一個元素儲存到int陣列中
            int[] arr = new int[strArray.length];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = Integer.parseInt(strArray[i]);
            }
            //對int陣列進行排序
            Arrays.sort(arr);
            //對排序後的陣列進行字串拼接
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < arr.length; i++) {
                if (i == arr.length - 1) {
                    sb.append(arr[i]);
                } else {
                    sb.append(arr[i]).append(" ");
                }
            }
            String result = sb.toString();
            System.out.println(result);
        }
    }
    

2.5自動拆箱和自動裝箱

  • 自動裝箱

    把基本資料型別轉換為對應的包裝類型別

  • 自動拆箱

    把包裝類型別轉換為對應的基本資料型別

  • 示例程式碼

    Integer i = 100; // 自動裝箱
    i += 200; // i = i + 200; i + 200 自動拆箱;i = i + 200; 是自動裝箱
    

3.時間日期類(JDK7)

3.1Date類

  • Date類

    Date代表了一個特定的時間,精確到毫秒

  • Date類的構造方法

    方法名說明
    public Date()分配一個Date物件,並初始化,以便它代表它被分配的時間,精確到毫秒
    public Date(long date)分配一個 Date物件,並將其初始化為表示從標準基準時間起指定的毫秒數
  • 示例程式碼

    public class dateDemo01 {
        public static void main(String[] args) {
            //public Date():分配一個 Date物件,並初始化,以便它代表它被分配的時間,精確到毫秒
            Date d1 = new Date();
            System.out.println(d1);//Tue Nov 03 10:27:28 CST 2020
            //public Date(long date):分配一個 Date物件,並將其初始化為表示從標準基準時間起指定的毫秒數
            long date = 1000*60*60;
            Date d2 = new Date(date);
            System.out.println(d2);//Thu Jan 01 09:00:00 CST 1970
        }
    }
    

3.2Date類的常用方法

  • 常用方法

    方法名說明
    public long getTime()獲取的是日期物件從1970年1月1日 00:00:00到現在的毫秒值
    public void setTime(long time)設定時間,給的是毫秒值
  • 示例程式碼

    public class DateDemo02 {
        public static void main(String[] args) {
            //建立日期物件
            Date d = new Date();
    
            //public long getTime():獲取的是日期物件從1970年1月1日 00:00:00到現在的毫秒值
            System.out.println(d.getTime());
            System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");
    
            //public void setTime(long time):設定時間,給的是毫秒值
    //        long time = 1000*60*60;
            long time = System.currentTimeMillis();
            d.setTime(time);
    
            System.out.println(d);
        }
    }
    

3.3SimpleDateFormat類

  • SimpleDateFormat類概述

    SimpleDateFormat是一個具體的類,用於以區域設定敏感的方式格式化和解析日期。

  • SimpleDateFormat類構造方法

    方法名說明
    public SimpleDateFormat()構造一個SimpleDateFormat,使用預設模式和日期格式
    public SimpleDateFormat(String pattern)構造一個SimpleDateFormat使用給定的模式和預設的日期 格
  • SimpleDateFormat類的常用方法

    • 格式化(從Date到String)
      • public final String format(Date date):將日期格式化成日期/時間字串
    • 解析(從String到Date)
      • public Date parse(String source):從給定字串的開始解析文字以生成日期
  • 示例程式碼

    public class SimpleDateFormatDemo01 {
        public static void main(String[] args) throws ParseException {
            //Date----String
            Date d = new Date();
    //        SimpleDateFormat sdf  = new SimpleDateFormat();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);
            System.out.println("--------");
            String ss = "2048-08-09 11:11:11";
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(ss);
            System.out.println(dd);
        }
    }
    

3.2Calendar類

  • Calendar類概述

    Calendar 為特定瞬間與一組日曆欄位之間的轉換提供了一些方法,併為操作日曆欄位提供了一些方法
    Calendar 提供了一個類方法 getInstance 用於獲取這種型別的一般有用的物件。
    該方法返回一個Calendar 物件。
    其日曆欄位已使用當前日期和時間初始化:Calendar rightNow = Calendar.getInstance();

  • Calendar類常用方法

方法名說明
public int get(int field)返回給定日曆欄位的值
public abstract void add(int field, int amount)根據日曆的規則,將指定的時間量新增或減去給定的日 歷字
public final void set(int year,int month,int date)設定當前日曆的年月日
  • 示例程式碼
public class CalendarDemo {
    public static void main(String[] args) {
        //獲取日曆類物件
        Calendar c = Calendar.getInstance();
        //public int get(int field):返回給定日曆欄位的值
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");//2020年11月3日

        //public abstract void add(int field, int amount):根據日曆的規則,將指定的時間量新增或減去給定的日曆欄位
        //需求1:3年前的今天
         c.add(Calendar.YEAR,-3);
         year = c.get(Calendar.YEAR);
         month = c.get(Calendar.MONTH) + 1;
         date = c.get(Calendar.DATE);
         System.out.println(year + "年" + month + "月" + date + "日");//2017年11月3日

         //需求2:10年後的10天前
         c.add(Calendar.YEAR,10);
         c.add(Calendar.DATE,-10);
         year = c.get(Calendar.YEAR);
         month = c.get(Calendar.MONTH) + 1;
         date = c.get(Calendar.DATE);
         System.out.println(year + "年" + month + "月" + date + "日");//2027年10月24日

        //public final void set(int year,int month,int date):設定當前日曆的年月日
        c.set(2050,10,10);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH) + 1;
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");//2050年11月10日
    }
}

3.6二月天案例

  • 需求:獲取任意一年的二月有多少天

  • 程式碼實現

    public class CalendarTest {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("請輸入年份");
            int year = sc.nextInt();
            Calendar c = Calendar.getInstance();
            //設定日曆物件的年、月、日
            c.set(year,2,1);
            //3月1日往前推一天,就是2月的最後一天
            c.add(Calendar.DATE,-1);
            //獲取這一天輸出即可
            int date = c.get(Calendar.DATE);
            System.out.println(year + "年的2月份有" + date + "天");
        }
    }
    

4.時間日期類(JDK8)

在JDK7以前使用Date類表示日期時間物件,但是想要對時間進行計算需要轉換成毫秒值手動計算比較麻煩。

JDK8以後新增了幾個和時間相關的類,提供了一些對時間計算的方法,用起來非常方便。

LocalDateTime: 年月日時分秒
LocalDate:      年月日
LocalTime:		時分秒
以上三個類都可以用來表示時間,他們的方法都是類似的,我們這裡以LocalDateTime為例做演示。 

4.1LocalDateTime獲取物件

public static LocalDateTime  now()
    獲取當前時間的物件
public static LocalDateTime  of(int y,int m,int d,int h,int m,int s)
    獲取指定時間的物件 

4.2LocalDateTime獲取方法

public int getYear()  
	獲取年
public int getMonthValue() 
    獲取年中的月
public int getDayOfMonth()  
    獲取月中的天
publc int getDayOfYear()  
    獲取年中的天
public DayOfWeek getDayOfWeek() 
    獲取星期幾
public int getHour()  
    獲取小時
public int getMinute()  
    獲取分鐘
public int getSecond()  
    獲取秒

4.3LocalDateTime轉換方法

public LocalDate toLocalDate()  
    把LocalDateTime轉換為LocalDate
public LocalTime toLocalTime()  
    把LocalDateTime轉換為LocalTime

4.4LocalDateTime格式化和解析

public String format(DateTimeFormatter formatter)  
    把LocalDateTime表示的時間轉換為String
    【注意:需要指定日期格式化器DateTimeFormatter】
    
public static LocalDateTime parse(CharSequence s, DateTimeFormatter m)  
    把String轉換為LocalDateTime
    【注意:需要指定日期格式化器DateTimeFormatter】
public class jdk8LocalDataTimeDemo04 {
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 12, 13, 14, 15);
        System.out.println(localDateTime);
        //Date->String
        //String format(DateTimeFormatter formatter) 使用指定的格式化程式格式化此日期時間。
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String format = localDateTime.format(pattern);
        System.out.println(format);
        //String->Data
        //static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)
        // 使用特定的格式化程式從文字字串獲取 LocalDateTime的例項
        String s = "2020年11月12日 13:14:15";
        LocalDateTime parse = LocalDateTime.parse(s, pattern);
        System.out.println(parse);
    }
}

4.5LocalDateTime加減方法

public LocalDateTime plusDays(long days) 
	增加、減少指定的天數
public LocalDateTime plusHours(long hours) 
	增加、減少指定的小時數
public LocalDateTime plusMinutes(long minutes) 
	增加、減少指定的分鐘數
public LocalDateTime plusMonths(long months) 
	增加、減少指定的月份數
public LocalDateTime plusNanos(long nanos) 
	增加、減少指定的納秒數
public LocalDateTime plusSeconds(long seconds) 
	增加、減少指定的秒數
public LocalDateTime plusWeeks(long weeks) 
	增加、減少指定的星期數
public LocalDateTime plusYears(long years) 
	增加、減少指定的年數

4.6LocalDateTime修改方法

public LocalDateTime withYear(int year) 
	修改年
public LocalDateTime withMonth(int month) 
	修改月份
public LocalDateTime withDayOfMonth(int dayOfMonth) 
	修改月中的天
public LocalDateTime withDayOfYear(int dayOfYear) 
	修改年中的天
public LocalDateTime withHour(int hour) 
	修改小時
public LocalDateTime withMinute(int minute) 
	修改分鐘
public LocalDateTime withSecond(int second) 
	修改秒

4.7Period和Duration時間間隔

Period和Duration都用來表示時間間隔
Period:表示年月日的時間間隔
Duration:表示天時分秒的時間間隔
  • Period的方法

    public static Period between(LocalDate date1,LocalDate date2)
    	獲取兩個LocalDate之間的時間間隔
    public int getDays() 
    	獲取此期間的天數。
    public int getMonths() 
    	獲取此期間的月數。  
    public int getYears() 
    	獲取此期間的年數。
    
  • Duration的方法

    public static Duration between(Temporal t1, Temporal t2)
    	獲取兩個時間之間的時間間隔物件
    public long toDays() 
    	獲取在此期間的天數。 
    public long toHours() 
    	獲取在此期間的幾個小時數。  
    public long toMillis() 
    	將此持續時間轉換為毫秒內的總長度。 
    public long toMinutes() 
    	獲取在此期間的分鐘數。 
    public longt toHoursPart();
    	獲取小時的部分
    public longt toMinteusPart();
    	獲取分鐘的部分
    public longt toSecondPart();
    	獲取秒中的部分
    

4.8練習1

  • 需求:鍵盤錄入一個年份看他是不是閏年

  • 程式碼實現

    public class test03 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("請輸入一個年份");
            String year = sc.nextLine();
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
            LocalDate localDate = LocalDate.parse(year, dtf);
            int year1 = localDate.getYear();
            LocalDate of = LocalDate.of(year1, 3, 1);
            LocalDate days = of.plusDays(-1);
            int dayOfMonth = days.getDayOfMonth();
    //        System.out.println(dayOfMonth);
            if (dayOfMonth == 29) {
                System.out.println(year + "是閏年");
            } else {
                System.out.println("是平年");
            }
        }
    }
    

4.9練習2

  • 需求:抽獎倒計時

  • 程式碼實現

    public class test04 {
        public static void main(String[] args) {
            LocalDateTime localDateTime = LocalDateTime.of(2021, 8, 24, 10, 0, 0);
            while (true) {
                LocalDateTime now = LocalDateTime.now();
                Duration duration = Duration.between(localDateTime, now);
                long day = duration.toDays();
                long hours = duration.toHoursPart();
                int minutes = duration.toMinutesPart();
                int seconds = duration.toSecondsPart();
                System.out.println("距離抽獎時間還有" + day + "天" + hours + "小時" + minutes + "分" + seconds + "秒");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

5.異常

5.1異常

  • 異常的概述 :異常就是程式出現了不正常的情況

  • 異常的體系結構

在這裡插入圖片描述

5.2JVM預設處理異常的方式

  • 如果程式出現了問題,我們沒有做任何處理,最終JVM 會做預設的處理,處理方式有如下兩個步驟
    • 把異常的名稱,錯誤原因及異常出現的位置等資訊輸出在了控制檯
    • 程式停止執行

5.3try-catch方式處理異常

  • 定義格式

    try{
    	可能出現異常的程式碼;
    }catch(異常類名 變數名) {
    	異常的處理程式碼;
    }
    
  • 執行流程

    • 程式從 try 裡面的程式碼開始執行
    • 出現異常,就會跳轉到對應的 catch 裡面去執行
    • 執行完畢之後,程式還可以繼續往下執行

5.4Throwable成員方法

  • 常用方法

    方法名說明
    public String getMessage()返回此 throwable 的詳細訊息字串
    public String toString()返回此可丟擲的簡短描述
    public void printStackTrace()把異常的錯誤資訊輸出在控制檯

5.5編譯時異常和執行時異常的區別

  • 編譯時異常
    • 都是Exception類及其子類
    • 必須顯示處理,否則程式就會發生錯誤,無法通過編譯
  • 執行時異常
    • 都是RuntimeException類及其子類
    • 無需顯示處理,也可以和編譯時異常一樣處理

5.6throws方式處理異常

  • 定義格式

    public void 方法() throws 異常類名 {
    }
    
  • 注意事項

    • 這個throws格式是跟在方法的括號後面的
    • 編譯時異常必須要進行處理,兩種處理方案:try…catch …或者 throws,如果採用 throws 這種方案,將來誰呼叫誰處理
    • 執行時異常可以不處理,出現問題後,需要我們回來修改程式碼

5.7throws和throw的區別

throwsthrow
用在方法聲明後面,跟的是異常類名用在方法體內,跟的是異常物件名
表示丟擲異常,由改方法的呼叫者來處理表示丟擲異常,由方法體內的語句處理
表示出現異常的一種可能性,並不一定會發生這些異常執行throw一定丟擲了某種異常