天天看點

throw_Keyword

throw and throws in Java

throw

Java中的throw關鍵字用于顯式地從方法或任何代碼塊中引發異常。我們可以抛出已檢查或未檢查的異常。throw關鍵字主要用于抛出自定義異常。

Syntax:

throw Instance

Example:

throw new ArithmeticException("/ by zero");      

But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.

但是這個例外就是,執行個體的類型必須為Throwable的或子類的Throwable。例如,Exception是Throwable的子類,使用者定義的異常通常擴充Exception類。與C ++不同,int,char,float或non-throwable類等資料類型不能用作異常。

The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.

執行throw語句後,程式的執行流程立即停止,并檢查最近的封閉try塊以檢視它是否具有與異常類型比對的catch語句。如果找到比對,則将受控轉移到該語句,否則檢查下一個封閉try塊,依此類推。如果未找到比對的catch,則預設異常處理程式将暫停程式。

// Java program that demonstrates the use of throw 
class ThrowExcep 
{ 
    static void fun() 
    { 
        try
        { 
            throw new NullPointerException("demo"); 
        } 
        catch(NullPointerException e) 
        { 
            System.out.println("Caught inside fun()."); 
            throw e; // rethrowing the exception 
        } 
    } 
  
    public static void main(String args[]) 
    { 
        try
        { 
            fun(); 
        } 
        catch(NullPointerException e) 
        { 
            System.out.println("Caught in main."); 
        } 
    } 
}      

Output:

Caught inside fun().
Caught in main.      

Another Example:

// Java program that demonstrates the use of throw 
class Test  
{ 
    public static void main(String[] args) 
    { 
        System.out.println(1/0); 
    } 
}      

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero      

throws關鍵字

throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.

throws是Java中的一個關鍵字,用于方法的簽名,以訓示此方法可能會抛出一個列出的類型異常。這些方法的調用者必須使用try-catch塊來處理異常。

Syntax

type method_name(parameters) throws exception_list      

exception_list is a comma separated list of all the

exceptions which a method might throw.

In a program, if there is a chance of rising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:

兩種方式異常處理

By using try catch

By using throws keyword

We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.

// Java program to illustrate error in case  
// of unhandled exception 
class tst  
{ 
    public static void main(String[] args) 
    { 
        Thread.sleep(10000); 
        System.out.println("Hello Geeks"); 
    } 
}      

Output:

error: unreported exception InterruptedException; must be caught or declared to be thrown      

Explanation : In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.

// Java program to illustrate throws 
class tst  
{ 
    public static void main(String[] args)throws InterruptedException 
    { 
        Thread.sleep(10000); 
        System.out.println("Hello Geeks"); 
    } 
}      

Output:

Hello Geeks      

Explanation : In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks

Another Example:

// Java program to demonstrate working of throws 
class ThrowsExecp 
{ 
    static void fun() throws IllegalAccessException 
    { 
        System.out.println("Inside fun(). "); 
        throw new IllegalAccessException("demo"); 
    } 
    public static void main(String args[]) 
    { 
        try
        { 
            fun(); 
        } 
        catch(IllegalAccessException e) 
        { 
            System.out.println("caught in main."); 
        } 
    } 
}      

Output:

Inside fun().
caught in main.      

關于throws關鍵字要記住的要點