exception js code example
Example 1: exception js
function div(){
let x = prompt('Entrez un premier nombre (numérateur)');
let y = prompt('Entrez un deuxième nombre (dénominateur)');
if(isNaN(x) || isNaN(y) || x == '' || y == ''){
throw new Error('Merci de rentrer deux nombres');
}else if(y == 0){
throw new Error('Division par 0 impossible')
}else{
alert(x / y);
}
}
try{
div();
}catch(err){
alert(err.message);
}finally{
alert('Ce message s\'affichera quoiqu\'il arrive');
}
Example 2: js errors
JS Error Name Values:
name
Sets or returns the error name
message
Sets or returns an error message in string from
EvalError
An error has occurred in the eval() function
RangeError
A number is “out of range”
ReferenceError
An illegal reference has occurred
SyntaxError
A syntax error has occurred
TypeError
A type error has occurred
URIError
An encodeURI() error has occurred
Example 3: javascript throw new error
throw new Error("Error message here"); // Uncaught Error: Error message here
Example 4: js throw custom error
class CustomError extends Error {
constructor(foo = 'bar', ...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor
super(...params)
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError)
}
this.name = 'CustomError'
// Custom debugging information
this.foo = foo
this.date = new Date()
}
}
try {
throw new CustomError('baz', 'bazMessage')
} catch(e) {
console.error(e.name) //CustomError
console.error(e.foo) //baz
console.error(e.message) //bazMessage
console.error(e.stack) //stacktrace
}
Example 5: javascript try catch
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword');
}
catch (e) {
document.write(e.message);
}
</script>
</body>
</html>