Home | History | Annotate | Download | only in io
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package libcore.io;
     18 
     19 import java.io.IOException;
     20 import java.net.SocketException;
     21 
     22 /**
     23  * A checked exception thrown when {@link Os} methods fail. This exception contains the native
     24  * errno value, for comparison against the constants in {@link OsConstants}, should sophisticated
     25  * callers need to adjust their behavior based on the exact failure.
     26  */
     27 public final class ErrnoException extends Exception {
     28     private final String functionName;
     29     public final int errno;
     30 
     31     public ErrnoException(String functionName, int errno) {
     32         this.functionName = functionName;
     33         this.errno = errno;
     34     }
     35 
     36     public ErrnoException(String functionName, int errno, Throwable cause) {
     37         super(cause);
     38         this.functionName = functionName;
     39         this.errno = errno;
     40     }
     41 
     42     /**
     43      * Converts the stashed function name and errno value to a human-readable string.
     44      * We do this here rather than in the constructor so that callers only pay for
     45      * this if they need it.
     46      */
     47     @Override public String getMessage() {
     48         String errnoName = OsConstants.errnoName(errno);
     49         if (errnoName == null) {
     50             errnoName = "errno " + errno;
     51         }
     52         String description = Libcore.os.strerror(errno);
     53         return functionName + " failed: " + errnoName + " (" + description + ")";
     54     }
     55 
     56     public IOException rethrowAsIOException() throws IOException {
     57         IOException newException = new IOException(getMessage());
     58         newException.initCause(this);
     59         throw newException;
     60     }
     61 
     62     public SocketException rethrowAsSocketException() throws SocketException {
     63         throw new SocketException(getMessage(), this);
     64     }
     65 }
     66