diff --git a/hands-on_dlang.md b/hands-on_dlang.md index 90ca607..c9b0594 100644 --- a/hands-on_dlang.md +++ b/hands-on_dlang.md @@ -71,6 +71,8 @@ - [Functions as arguments](#functions-as-arguments) - [Local functions with context](#local-functions-with-context) - [Anonymous functions and lambdas](#anonymous-functions-and-lambdas) + - [Exceptions](#exceptions) + - [`nothrow`](#nothrow) ## Setup @@ -1062,3 +1064,46 @@ These are often passed as template arguments in the functional parts of Phobos: ```D [1, 2, 3].reduce!((a, b) => a + b)(); ``` + +### Exceptions +Exceptions in D are very similar to Exceptions in Java: + +```D +class MyException : Exception { + this(string msg) { + super("MyException was thrown because of " ~ msg); + } +} + +try { + throw new MyException("no reason"); +} +catch (FileException e) { // not caught here + /* … */ +} +catch (MyException e) { // but here + /* … */ +} +finally { // executed regardless of whether an exception was thrown or not + /* … */ +} +``` + +#### `nothrow` + +The compiler can enforce that a function can not throw an exception. You can +achieve this by annotating a function with `nothrow`: + +```D +import std.exception: enforce; // convenience function which throws if `false` is passed + +int divide(int a, int b) { + enforce(b != 0, "Can't divide by 0!"); + return a / b; +} + +int divide4By2() nothrow { + return divide(4, 2); // error, divide my throw +} + +``` \ No newline at end of file