跳轉到內容

Java 程式設計/關鍵字/throw

來自華夏公益教科書,開放的書籍,為開放的世界

throw 是一個關鍵字;它 '丟擲' 一個異常。在 throw 語句中,可以丟擲的三種類型的物件是:Exceptionjava:Throwablejava:Error

語法

throw <Exception Ref>;

例如

Computer code
public Customer findCustomer( String name ) throws '''CustomerNotFoundException'''
 {
    Customer custRet = null;
 
    Iterator iter = _customerList.iterator();
    while ( iter.hasNext() )
    {
        Customer cust = (Customer) iter.next();
        if ( cust.getName().equals( name ) )
        {
           // --- Customer find --
           custRet = cust;
           break;
        }
     }
     if ( custRet == null )
     {
        // --- Customer not found ---
        throw new '''CustomerNotFoundException'''( "Customer "+ name + " was not found" );
     }
 
    return custRet
  }


華夏公益教科書