add section about exceptions
This commit is contained in:
parent
35a2431739
commit
757a4b8d49
1 changed files with 45 additions and 0 deletions
|
@ -71,6 +71,8 @@
|
||||||
- [Functions as arguments](#functions-as-arguments)
|
- [Functions as arguments](#functions-as-arguments)
|
||||||
- [Local functions with context](#local-functions-with-context)
|
- [Local functions with context](#local-functions-with-context)
|
||||||
- [Anonymous functions and lambdas](#anonymous-functions-and-lambdas)
|
- [Anonymous functions and lambdas](#anonymous-functions-and-lambdas)
|
||||||
|
- [Exceptions](#exceptions)
|
||||||
|
- [`nothrow`](#nothrow)
|
||||||
|
|
||||||
## Setup
|
## Setup
|
||||||
|
|
||||||
|
@ -1062,3 +1064,46 @@ These are often passed as template arguments in the functional parts of Phobos:
|
||||||
```D
|
```D
|
||||||
[1, 2, 3].reduce!((a, b) => a + b)();
|
[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
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
Loading…
Reference in a new issue