跳转到内容

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
  }


华夏公益教科书