1 package org.djunits; 2 3 import static org.junit.Assert.fail; 4 5 /** 6 * Use the Try class as follows: 7 * 8 * <pre> 9 * new Try( 10 * public @Override void execute() 11 * { 12 * // code to test that should fail 13 * }).test(); 14 * </pre> 15 * <p> 16 * Copyright (c) 2019-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br> 17 * BSD-style license. See <a href="https://djunits.org/docs/license.html">DJUNITS License</a>. 18 * <p> 19 * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a> 20 */ 21 public abstract class Try 22 { 23 /** implement the execute method to test failure. */ 24 public abstract void execute(); 25 26 /** call the test method to test failure of the try. */ 27 public void test() 28 { 29 test("method should have thrown an exception"); 30 } 31 32 /** 33 * call the test method to test failure of the try. 34 * @param message the message to print 35 */ 36 public void test(final String message) 37 { 38 try 39 { 40 execute(); 41 fail(message); 42 } 43 catch (Exception e) 44 { 45 // ok! 46 } 47 } 48 49 /** 50 * call the test method to test failure of the try with an expected exception type. 51 * @param message the message to print 52 * @param expectedExceptionClass the expected exception 53 */ 54 public void test(final String message, final Class<? extends Exception> expectedExceptionClass) 55 { 56 try 57 { 58 execute(); 59 fail(message); 60 } 61 catch (Exception e) 62 { 63 if (!expectedExceptionClass.isInstance(e)) 64 { 65 fail(message + ", unexcepted exception: " + e.getClass().getSimpleName()); 66 } 67 } 68 } 69 }