Debian Codegraph @

libphobos/testsuite/libphobos.phobos/std_exception.d

raw
1 @system unittest
2 {
3 import std.exception;
4
5 import core.stdc.stdlib : malloc, free;
6 import std.algorithm.comparison : equal;
7 import std.algorithm.iteration : map, splitter;
8 import std.algorithm.searching : endsWith;
9 import std.conv : ConvException, to;
10 import std.range : front, retro;
11
12 // use enforce like assert
13 int a = 3;
14 enforce(a > 2, "a needs to be higher than 2.");
15
16 // enforce can throw a custom exception
17 enforce!ConvException(a > 2, "a needs to be higher than 2.");
18
19 // enforce will return it's input
20 enum size = 42;
21 auto memory = enforce(malloc(size), "malloc failed")[0 .. size];
22 scope(exit) free(memory.ptr);
23
24 // collectException can be used to test for exceptions
25 Exception e = collectException("abc".to!int);
26 assert(e.file.endsWith("conv.d"));
27
28 // and just for the exception message
29 string msg = collectExceptionMsg("abc".to!int);
30 assert(msg == "Unexpected 'a' when converting from type string to type int");
31
32 // assertThrown can be used to assert that an exception is thrown
33 assertThrown!ConvException("abc".to!int);
34
35 // ifThrown can be used to provide a default value if an exception is thrown
36 assert("x".to!int().ifThrown(0) == 0);
37
38 // handle is a more advanced version of ifThrown for ranges
39 auto r = "12,1337z32,54".splitter(',').map!(a => to!int(a));
40 auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0);
41 assert(h.equal([12, 0, 54]));
42 assertThrown!ConvException(h.retro.equal([54, 0, 12]));
43
44 // basicExceptionCtors avoids the boilerplate when creating custom exceptions
45 static class MeaCulpa : Exception
46 {
47 mixin basicExceptionCtors;
48 }
49 e = collectException((){throw new MeaCulpa("diagnostic message");}());
50 assert(e.msg == "diagnostic message");
51 assert(e.file == __FILE__);
52 assert(e.line == __LINE__ - 3);
53
54 // assumeWontThrow can be used to cast throwing code into `nothrow`
55 void exceptionFreeCode() nothrow
56 {
57 // auto-decoding only throws if an invalid UTF char is given
58 assumeWontThrow("abc".front);
59 }
60
61 // assumeUnique can be used to cast mutable instance to an `immutable` one
62 // use with care
63 char[] str = " mutable".dup;
64 str[0 .. 2] = "im";
65 immutable res = assumeUnique(str);
66 assert(res == "immutable");
67 }
68
69 @system unittest
70 {
71 import std.exception;
72
73 import core.exception : AssertError;
74
75 import std.string;
76 assertNotThrown!StringException(enforce!StringException(true, "Error!"));
77
78 //Exception is the default.
79 assertNotThrown(enforce!StringException(true, "Error!"));
80
81 assert(collectExceptionMsg!AssertError(assertNotThrown!StringException(
82 enforce!StringException(false, "Error!"))) ==
83 `assertNotThrown failed: StringException was thrown: Error!`);
84 }
85
86 @system unittest
87 {
88 import std.exception;
89
90 import core.exception : AssertError;
91 import std.string;
92
93 assertThrown!StringException(enforce!StringException(false, "Error!"));
94
95 //Exception is the default.
96 assertThrown(enforce!StringException(false, "Error!"));
97
98 assert(collectExceptionMsg!AssertError(assertThrown!StringException(
99 enforce!StringException(true, "Error!"))) ==
100 `assertThrown failed: No StringException was thrown.`);
101 }
102
103 @system unittest
104 {
105 import std.exception;
106
107 import core.stdc.stdlib : malloc, free;
108 import std.conv : ConvException, to;
109
110 // use enforce like assert
111 int a = 3;
112 enforce(a > 2, "a needs to be higher than 2.");
113
114 // enforce can throw a custom exception
115 enforce!ConvException(a > 2, "a needs to be higher than 2.");
116
117 // enforce will return it's input
118 enum size = 42;
119 auto memory = enforce(malloc(size), "malloc failed")[0 .. size];
120 scope(exit) free(memory.ptr);
121 }
122
123 @safe unittest
124 {
125 import std.exception;
126
127 assertNotThrown(enforce(true, new Exception("this should not be thrown")));
128 assertThrown(enforce(false, new Exception("this should be thrown")));
129 }
130
131 @safe unittest
132 {
133 import std.exception;
134
135 assert(enforce(123) == 123);
136
137 try
138 {
139 enforce(false, "error");
140 assert(false);
141 }
142 catch (Exception e)
143 {
144 assert(e.msg == "error");
145 assert(e.file == __FILE__);
146 assert(e.line == __LINE__-7);
147 }
148 }
149
150 @safe unittest
151 {
152 import std.exception;
153
154 import std.conv : ConvException;
155 alias convEnforce = enforce!ConvException;
156 assertNotThrown(convEnforce(true));
157 assertThrown!ConvException(convEnforce(false, "blah"));
158 }
159
160 @system unittest
161 {
162 import std.exception;
163
164 import core.stdc.stdio : fclose, fgets, fopen;
165 import std.file : thisExePath;
166 import std.string : toStringz;
167
168 auto f = fopen(thisExePath.toStringz, "r").errnoEnforce;
169 scope(exit) fclose(f);
170 char[100] buf;
171 auto line = fgets(buf.ptr, buf.length, f);
172 enforce(line !is null); // expect a non-empty line
173 }
174
175 @system unittest
176 {
177 import std.exception;
178
179 int b;
180 int foo() { throw new Exception("blah"); }
181 assert(collectException(foo(), b));
182
183 version (D_NoBoundsChecks) {}
184 else
185 {
186 // check for out of bounds error
187 int[] a = new int[3];
188 import core.exception : RangeError;
189 assert(collectException!RangeError(a[4], b));
190 }
191 }
192
193 @safe unittest
194 {
195 import std.exception;
196
197 int foo() { throw new Exception("blah"); }
198 assert(collectException(foo()).msg == "blah");
199 }
200
201 @safe unittest
202 {
203 import std.exception;
204
205 void throwFunc() { throw new Exception("My Message."); }
206 assert(collectExceptionMsg(throwFunc()) == "My Message.");
207
208 void nothrowFunc() {}
209 assert(collectExceptionMsg(nothrowFunc()) is null);
210
211 void throwEmptyFunc() { throw new Exception(""); }
212 assert(collectExceptionMsg(throwEmptyFunc()) == emptyExceptionMsg);
213 }
214
215 @system unittest
216 {
217 import std.exception;
218
219 int[] arr = new int[1];
220 auto arr1 = arr.assumeUnique;
221 static assert(is(typeof(arr1) == immutable(int)[]));
222 assert(arr == null);
223 assert(arr1 == [0]);
224 }
225
226 @system unittest
227 {
228 import std.exception;
229
230 int[string] arr = ["a":1];
231 auto arr1 = arr.assumeUnique;
232 static assert(is(typeof(arr1) == immutable(int[string])));
233 assert(arr == null);
234 assert(arr1.keys == ["a"]);
235 }
236
237 @safe unittest
238 {
239 import std.exception;
240
241 import std.math.algebraic : sqrt;
242
243 // This function may throw.
244 int squareRoot(int x)
245 {
246 if (x < 0)
247 throw new Exception("Tried to take root of negative number");
248 return cast(int) sqrt(cast(double) x);
249 }
250
251 // This function never throws.
252 int computeLength(int x, int y) nothrow
253 {
254 // Since x*x + y*y is always positive, we can safely assume squareRoot
255 // won't throw, and use it to implement this nothrow function. If it
256 // does throw (e.g., if x*x + y*y overflows a 32-bit value), then the
257 // program will terminate.
258 return assumeWontThrow(squareRoot(x*x + y*y));
259 }
260
261 assert(computeLength(3, 4) == 5);
262 }
263
264 @system unittest
265 {
266 import std.exception;
267
268 int i = 0;
269 int* p = null;
270 assert(!p.doesPointTo(i));
271 p = &i;
272 assert( p.doesPointTo(i));
273 }
274
275 @system unittest
276 {
277 import std.exception;
278
279 struct S
280 {
281 int v;
282 int* p;
283 }
284 int i;
285 auto s = S(0, &i);
286
287 // structs and unions "own" their members
288 // pointsTo will answer true if one of the members pointsTo.
289 assert(!s.doesPointTo(s.v)); //s.v is just v member of s, so not pointed.
290 assert( s.p.doesPointTo(i)); //i is pointed by s.p.
291 assert( s .doesPointTo(i)); //which means i is pointed by s itself.
292
293 // Unions will behave exactly the same. Points to will check each "member"
294 // individually, even if they share the same memory
295 }
296
297 @system unittest
298 {
299 import std.exception;
300
301 int i;
302 // trick the compiler when initializing slice
303 // https://issues.dlang.org/show_bug.cgi?id=18637
304 int* p = &i;
305 int[] slice = [0, 1, 2, 3, 4];
306 int[5] arr = [0, 1, 2, 3, 4];
307 int*[] slicep = [p];
308 int*[1] arrp = [&i];
309
310 // A slice points to all of its members:
311 assert( slice.doesPointTo(slice[3]));
312 assert(!slice[0 .. 2].doesPointTo(slice[3])); // Object 3 is outside of the
313 // slice [0 .. 2]
314
315 // Note that a slice will not take into account what its members point to.
316 assert( slicep[0].doesPointTo(i));
317 assert(!slicep .doesPointTo(i));
318
319 // static arrays are objects that own their members, just like structs:
320 assert(!arr.doesPointTo(arr[0])); // arr[0] is just a member of arr, so not
321 // pointed.
322 assert( arrp[0].doesPointTo(i)); // i is pointed by arrp[0].
323 assert( arrp .doesPointTo(i)); // which means i is pointed by arrp
324 // itself.
325
326 // Notice the difference between static and dynamic arrays:
327 assert(!arr .doesPointTo(arr[0]));
328 assert( arr[].doesPointTo(arr[0]));
329 assert( arrp .doesPointTo(i));
330 assert(!arrp[].doesPointTo(i));
331 }
332
333 @system unittest
334 {
335 import std.exception;
336
337 class C
338 {
339 this(int* p){this.p = p;}
340 int* p;
341 }
342 int i;
343 C a = new C(&i);
344 C b = a;
345
346 // Classes are a bit particular, as they are treated like simple pointers
347 // to a class payload.
348 assert( a.p.doesPointTo(i)); // a.p points to i.
349 assert(!a .doesPointTo(i)); // Yet a itself does not point i.
350
351 //To check the class payload itself, iterate on its members:
352 ()
353 {
354 import std.traits : Fields;
355
356 foreach (index, _; Fields!C)
357 if (doesPointTo(a.tupleof[index], i))
358 return;
359 assert(0);
360 }();
361
362 // To check if a class points a specific payload, a direct memmory check
363 // can be done:
364 auto aLoc = cast(ubyte[__traits(classInstanceSize, C)]*) a;
365 assert(b.doesPointTo(*aLoc)); // b points to where a is pointing
366 }
367
368 @safe unittest
369 {
370 import std.exception;
371
372 import core.stdc.errno : EAGAIN;
373 auto ex = new ErrnoException("oh no", EAGAIN);
374 assert(ex.errno == EAGAIN);
375 }
376
377 @safe unittest
378 {
379 import std.exception;
380
381 import core.stdc.errno : errno, EAGAIN;
382
383 auto old = errno;
384 scope(exit) errno = old;
385
386 // fake that errno got set by the callee
387 errno = EAGAIN;
388 auto ex = new ErrnoException("oh no");
389 assert(ex.errno == EAGAIN);
390 }
391
392 @safe unittest
393 {
394 import std.exception;
395
396 import std.conv : to;
397 assert("x".to!int.ifThrown(0) == 0);
398 }
399
400 @safe unittest
401 {
402 import std.exception;
403
404 import std.conv : ConvException, to;
405 string s = "true";
406 assert(s.to!int.ifThrown(cast(int) s.to!double)
407 .ifThrown(cast(int) s.to!bool) == 1);
408
409 s = "2.0";
410 assert(s.to!int.ifThrown(cast(int) s.to!double)
411 .ifThrown(cast(int) s.to!bool) == 2);
412
413 // Respond differently to different types of errors
414 alias orFallback = (lazy a) => a.ifThrown!ConvException("not a number")
415 .ifThrown!Exception("number too small");
416
417 assert(orFallback(enforce("x".to!int < 1).to!string) == "not a number");
418 assert(orFallback(enforce("2".to!int < 1).to!string) == "number too small");
419 }
420
421 @safe unittest
422 {
423 import std.exception;
424
425 // null and new Object have a common type(Object).
426 static assert(is(typeof(null.ifThrown(new Object())) == Object));
427 static assert(is(typeof((new Object()).ifThrown(null)) == Object));
428
429 // 1 and new Object do not have a common type.
430 static assert(!__traits(compiles, 1.ifThrown(new Object())));
431 static assert(!__traits(compiles, (new Object()).ifThrown(1)));
432 }
433
434 @system unittest
435 {
436 import std.exception;
437
438 import std.format : format;
439 assert("%s".format.ifThrown!Exception(e => typeid(e).name) == "std.format.FormatException");
440 }
441
442 pure @safe unittest
443 {
444 import std.exception;
445
446 import std.algorithm.comparison : equal;
447 import std.algorithm.iteration : map, splitter;
448 import std.conv : to, ConvException;
449
450 auto s = "12,1337z32,54,2,7,9,1z,6,8";
451
452 // The next line composition will throw when iterated
453 // as some elements of the input do not convert to integer
454 auto r = s.splitter(',').map!(a => to!int(a));
455
456 // Substitute 0 for cases of ConvException
457 auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0);
458 assert(h.equal([12, 0, 54, 2, 7, 9, 0, 6, 8]));
459 }
460
461 pure @safe unittest
462 {
463 import std.exception;
464
465 import std.algorithm.comparison : equal;
466 import std.range : retro;
467 import std.utf : UTFException;
468
469 auto str = "hello\xFFworld"; // 0xFF is an invalid UTF-8 code unit
470
471 auto handled = str.handle!(UTFException, RangePrimitive.access,
472 (e, r) => ' '); // Replace invalid code points with spaces
473
474 assert(handled.equal("hello world")); // `front` is handled,
475 assert(handled.retro.equal("dlrow olleh")); // as well as `back`
476 }
477
478 pure @safe unittest
479 {
480 import std.exception;
481
482 import std.algorithm.comparison : equal;
483 import std.algorithm.iteration : map, splitter;
484 import std.conv : to, ConvException;
485
486 auto s = "12,1337z32,54,2,7,9,1z,6,8";
487
488 // The next line composition will throw when iterated
489 // as some elements of the input do not convert to integer
490 auto r = s.splitter(',').map!(a => to!int(a));
491
492 // Substitute 0 for cases of ConvException
493 auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0);
494 assert(h.equal([12, 0, 54, 2, 7, 9, 0, 6, 8]));
495 }
496
497 pure @safe unittest
498 {
499 import std.exception;
500
501 import std.algorithm.comparison : equal;
502 import std.range : retro;
503 import std.utf : UTFException;
504
505 auto str = "hello\xFFworld"; // 0xFF is an invalid UTF-8 code unit
506
507 auto handled = str.handle!(UTFException, RangePrimitive.access,
508 (e, r) => ' '); // Replace invalid code points with spaces
509
510 assert(handled.equal("hello world")); // `front` is handled,
511 assert(handled.retro.equal("dlrow olleh")); // as well as `back`
512 }
513
514 @safe unittest
515 {
516 import std.exception;
517
518 class MeaCulpa: Exception
519 {
520 ///
521 mixin basicExceptionCtors;
522 }
523
524 try
525 throw new MeaCulpa("test");
526 catch (MeaCulpa e)
527 {
528 assert(e.msg == "test");
529 assert(e.file == __FILE__);
530 assert(e.line == __LINE__ - 5);
531 }
532 }
533
534 @safe pure nothrow unittest
535 {
536 import std.exception;
537
538 class TestException : Exception { mixin basicExceptionCtors; }
539 auto e = new Exception("msg");
540 auto te1 = new TestException("foo");
541 auto te2 = new TestException("foo", e);
542 }
543