What are Nothrow functions in D-Language?

What is a function?

Functions are generally block codes that carry out certain execution in an application. This block of codes can be called more than once during the run time or execution time of the application.

What are Nothrow functions?

Nothrow functions generally abhor or restrict the trigger of an error.

Syntax

int functionName(arguments) nothrow {
try {
} catch (Exception error) { // catches all exceptions
}
}

In syntax, we use the nothrow keyword. Without this keyword the function will be like every other normal function.

Example

Let’s see an example:

import std.stdio;
int addition(int x, int y) nothrow {
int output;
try {
output = x + y;
} catch (Exception error) { // catches all exceptions
}
return output;
}
void main() {
writeln("the sum of x and y is ", addition(73,27));
}

Explanation

  • Line 2: We create a nothrow function addition and according to our syntax, we use the keyword nothrow after the (), as soon as we pass our arguments.

  • Line 3: We declare an output variable which we also use in line 11 to return the output of the function.

  • Lines 5 to 9: We use a try{}catch(){} method. We enter the logic of the function inside the try{}.

  • Line 6: We write the logic for the addition function output = x+y.

  • Line 7: We use the catch(){} to catch all available exceptions.

  • Line 10: We return the output variable so that when it is called we see the sum of x and y.

  • Line 14: We print to the screen and also call the addition function in which we pass some values for the function to add.

Free Resources