1. 程式人生 > >throws和throw assert

throws和throw assert

throws throws :用在方法上,明確表示該方法會產生異常,但是方法內部不做處理,將異常拋給呼叫處。呼叫處必須進行異常處理。異常後面的語句不再執行。

public class Throw1
{
    public static void main(String[] args)
    {
        //主方法中呼叫用throws宣告的方法,必須進行異常處理
        try
        {
            calu(10,0);
        }
        catch (Exception e)  //處理異常
        {
            e.printStackTrace(); 
        }
        System.out.println("********");  //會列印
    }
    public  static  int calu(int a,int b) throws Exception  //將異常拋給呼叫處
    {
        int result= a/b;
        System.out.println("#####"); //產生異常後,異常後面的語句不再執行
        return result;
    }
}

主方法也可以throws,是讓JVM處理異常,然後主方法異常後面的語句不再執行

public class Throw1
{
    public static void main(String[] args) throws Exception  //將異常拋給JVM
    {
        calu(10,0);
        System.out.println("********");  //不會列印
    }
    public  static  int calu(int a,int b) throws Exception  //將異常拋給呼叫處
    {
        int result= a/b;
        System.out.println("#####"); //產生異常後,異常後面的語句不再執行
        return result;
    }
}

在這裡插入圖片描述

數值轉換異常: 在這裡插入圖片描述 throw throw:用在方法中。由使用者產生異常類物件,而非JVM產生,一般與自定義異常搭配使用。 下面程式碼自定義異常: 比如在微信紅包中,一次最多是200元,超過200會出已異常:

/////throw
class MyException extends Exception
{
      public MyException(String str)
      {
          super(str);
      }
}
public class Throw1
{
    public static void main(String[] args) throws Exception  //將異常拋給JVM
    {
        try
        {
            int num=300;
            if(num>200)
              throw new MyException("微信紅包至多200元");
        }
        catch (MyException e)
        {
            e.printStackTrace();
        }
    }
}

在這裡插入圖片描述 面試題:請解釋throw和throws的區別 1. throw用於方法內部,主要表示手工異常丟擲。 2. throws主要在方法宣告上使用,明確告訴使用者本方法可能產生的異常,同時該方法可能不處理此異常。

現在要求編寫一個方法進行除法操作,但是對於此方法有如下要求:

  1. 在進行除法計算操作之前列印一行語句"**".
  2. 如果在除法計算過程中出現錯誤,則應該將異常返回給呼叫處。
  3. 不管最終是否有異常產生,都要求列印一行計算結果資訊。 在方法內拋異常,用在產生異常處處理異常將異常丟擲:
public class Throw1
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println(cual(10,0));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    public static int cual(int a,int b) 
    {
        int result=0;
        System.out.println("******");
        try {
            result=a/b;
        }catch (Exception e)
        {
            throw  e;
        }finally {
            System.out.println(result);
        }
        return result;
    }
}

直接在方法上throws

public static int cual(int a,int b) throws Exception
    {
        int result=0;
        System.out.println("******");
        try {
            result=a/b;
        }finally {
            System.out.println(result);
        }
        return result;
  }

assert 語法: assert 布林表示式:“返回false執行的程式碼塊” 當斷言返回false時會丟擲斷言異常。異常後面語句不會執行。

java 斷言開啟引數(JVM引數)為 -ea,預設 斷言關閉

public class Throw1
{
    public static void main(String[] args)
    {
        int num=10;
        assert num==55 :"num應該為55";
        System.out.println(num);
    }
}

在這裡插入圖片描述