|
15 | 15 | */ |
16 | 16 | package rx.exceptions; |
17 | 17 |
|
18 | | -import java.util.HashSet; |
19 | | -import java.util.Set; |
| 18 | +import java.util.*; |
20 | 19 |
|
21 | 20 | /** |
22 | 21 | * @warn javadoc class description missing |
@@ -148,5 +147,32 @@ public static Throwable getFinalCause(Throwable e) { |
148 | 147 | } |
149 | 148 | return e; |
150 | 149 | } |
151 | | - |
| 150 | + /** |
| 151 | + * Throws a single or multiple exceptions contained in the collection, wrapping it into |
| 152 | + * {@code CompositeException} if necessary. |
| 153 | + * @param exceptions the collection of exceptions. If null or empty, no exception is thrown. |
| 154 | + * If the collection contains a single exception, that exception is either thrown as-is or wrapped into a |
| 155 | + * CompositeException. Multiple exceptions are wrapped into a CompositeException. |
| 156 | + * @param whileText the circumstance string to be appended to the thrown CompositeException, inserted after |
| 157 | + * the sentences "Exception" and "Multiple exceptions". |
| 158 | + */ |
| 159 | + public static void throwIfAny(Collection<? extends Throwable> exceptions, String whileText) { |
| 160 | + if (exceptions != null && !exceptions.isEmpty()) { |
| 161 | + if (exceptions.size() == 1) { |
| 162 | + Throwable t = exceptions.iterator().next(); |
| 163 | + if (t instanceof RuntimeException) { |
| 164 | + throw (RuntimeException) t; |
| 165 | + } else |
| 166 | + if (t instanceof Error) { |
| 167 | + throw (Error) t; |
| 168 | + } else { |
| 169 | + throw new CompositeException( |
| 170 | + "Exception" + whileText, exceptions); |
| 171 | + } |
| 172 | + } else { |
| 173 | + throw new CompositeException( |
| 174 | + "Multiple exceptions" + whileText, exceptions); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
152 | 178 | } |
0 commit comments