Here you can find the source of toRuntimeException(Throwable t)
This method is usually called to convert checked Exceptions into unchecked ones.
Parameter | Description |
---|---|
t | the original cause; may be null |
public static RuntimeException toRuntimeException(Throwable t)
//package com.java2s; /*//from w ww . j ava2 s.c o m Copyright ? 2008 Brent Boyer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program (see the license directory in this project). If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * Always returns a RuntimeException using this sequential logic: * <ol> * <li>if t == null, returns a new RuntimeException which has a null cause</li> * <li>else if t is an instanceof Error, returns a new RuntimeException which has t as its cause</li> * <li>else if t is an instanceof RuntimeException, returns t <i>itself</i></li> * <li> * else if t is an instanceof Exception, then it must be a checked Exception, * so it returns a new RuntimeException which has t as its cause * </li> * <li> * else t is an actual Throwable instance (or some unknown subclass), * so it returns a new RuntimeException which has t as its cause * </li> * </ol> * <p> * This method is usually called to convert checked Exceptions into unchecked ones. * <p> * One example where this is useful is if you want to initialize a field by calling a method: * it turns out that such a method cannot throw a checked Exception, * so it must have a try-catch block, * and it may be convenient for the catch to simply pass whatever it catches to this method and rethrow the result. * <p> * @param t the original cause; may be null */ public static RuntimeException toRuntimeException(Throwable t) { if (t == null) return new RuntimeException("This RuntimeException wraps a null cause"); else if (t instanceof Error) return new RuntimeException("This RuntimeException wraps an underlying Error (see cause)", t); else if (t instanceof RuntimeException) return (RuntimeException) t; else if (t instanceof Exception) return new RuntimeException("This RuntimeException wraps an underlying checked Exception (see cause)", t); else return new RuntimeException("This RuntimeException wraps an underlying Throwable (see cause)", t); } }