Home | History | Annotate | Download | only in internal
      1 /**
      2  * Copyright (C) 2010 Google Inc.
      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 com.google.inject.internal;
     18 
     19 
     20 /**
     21  * Rethrows user-code exceptions in wrapped exceptions so that Errors can target the correct
     22  * exception.
     23  *
     24  * @author sameb (at) google.com (Sam Berlin)
     25  */
     26 class Exceptions {
     27 
     28   /**
     29    * Rethrows the exception (or it's cause, if it has one) directly if possible.
     30    * If it was a checked exception, this wraps the exception in a stack trace
     31    * with no frames, so that the exception is shown immediately with no frames
     32    * above it.
     33    */
     34   public static RuntimeException rethrowCause(Throwable throwable) {
     35     Throwable cause = throwable;
     36     if(cause.getCause() != null) {
     37       cause = cause.getCause();
     38     }
     39     return rethrow(cause);
     40   }
     41 
     42   /** Rethrows the exception. */
     43   public static RuntimeException rethrow(Throwable throwable) {
     44     if(throwable instanceof RuntimeException) {
     45       throw (RuntimeException)throwable;
     46     } else if(throwable instanceof Error) {
     47       throw (Error)throwable;
     48     } else {
     49       throw new UnhandledCheckedUserException(throwable);
     50     }
     51   }
     52 
     53   /**
     54    * A marker exception class that we look for in order to unwrap the exception
     55    * into the user exception, to provide a cleaner stack trace.
     56    */
     57   static class UnhandledCheckedUserException extends RuntimeException {
     58     public UnhandledCheckedUserException(Throwable cause) {
     59       super(cause);
     60     }
     61   }
     62 }
     63