关于抛异常
今天早上,同事拿了一段代码来问原因,我们讨论了一下:
@Test public void testThrow(){ try{ throw new RuntimeException("123"); } catch (Exception e){ System.out.println(e.getCause().getLocalizedMessage()); } }
代码很简单,不过很有意思,抛出了NullPointerException,什么情况下会出这种事呢,e肯定不是null,那原因就一定是null了:
/** * Returns the cause of this throwable or {@code null} if the * cause is nonexistent or unknown. (The cause is the throwable that * caused this throwable to get thrown.) * * <p>This implementation returns the cause that was supplied via one of * the constructors requiring a {@code Throwable}, or that was set after * creation with the {@link #initCause(Throwable)} method. While it is * typically unnecessary to override this method, a subclass can override * it to return a cause set by some other means. This is appropriate for * a "legacy chained throwable" that predates the addition of chained * exceptions to {@code Throwable}. Note that it is <i>not</i> * necessary to override any of the {@code PrintStackTrace} methods, * all of which invoke the {@code getCause} method to determine the * cause of a throwable. * * @return the cause of this throwable or {@code null} if the * cause is nonexistent or unknown. * @since 1.4 */ public synchronized Throwable getCause() { return (cause==this ? null : cause); }
它判断了下如果原因就是异常本身,那就把原因置为null,因为它认为原因是未知的。这个有点意思,异常的原因就是异常怎么产生的,但是当它发现和自己一样的时候,就说明不知道是什么,所以就是null了:>。
那怎么办呢,传个原因给它呗:
@Test public void testThrow(){ try{ throw new RuntimeException("123", new Throwable("cause:aaa")); } catch (Exception e){ System.out.println(e.getCause().getLocalizedMessage()); } }
==========================================================
咱最近用的github:https://github.com/saaavsaaa
微信公众号:
转载请注明出处