Quick actions

cmd+k|ctrl+k

Navigation

Languages

js-add-with-exception

Snippet info

Language

JavaScript

Visibility

public

Author

prodreg

Created

2017-03-17T15:06:28Z

Updated

2017-03-17T15:06:28Z

/* 
    Sources:
    https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/throw
*/

function OutOfRangeException(functionName, paramName, value) {
    this.message = 'Function "' + arguments.callee.name + '" with parameter "' + paramName + '" and value ' + value + '"' + ' is out of range. Only values x with -100 <= x <= 1000 are allowed.';
    this.name = 'OutOfRangeException';
}

function add(param1, param2) {
    if( (-100 <= param1) && (param1 <= 1000) ) {
        if( (-100 <= param2) && (param2 <= 1000) ) {
            return param1+param2;
        } else {
            throw new OutOfRangeException('add', 'param2', param2);
        }
    } else {
        throw new OutOfRangeException('add', 'param1', param1);
    }
}

try {
    console.log(add(-10, 10000));
} catch(e) {
    console.log('Error:');
    console.log(e);
}
INFO