DEV Community

aryan015
aryan015

Posted on • Updated on

Error handling by aryan🤣

❤

Error Handling

Error handling is the technique to handle different kinds of error in application. It usually consists of try, catch and finally keyword.

try{
    let a= 1;
    let b = 0;
    let c = a/b; // cannot divide by 0
}
catch(err){
console.log(err.message)
}
finally{
    // it will run irrespective of try and catch
    console.log('done')
}
Enter fullscreen mode Exit fullscreen mode

output

//error message
done
Enter fullscreen mode Exit fullscreen mode

Throw custom error

You can throw custom error by throw keyword.

try{
    let num =  1;
    let den = 0;
    if(den==0){
        throw 'denominator cannot be zero';
    }
}
catch(err){
    console.log(err.message) //denominator cannot be zero
}
finally{
    console.log('please retry')
}
Enter fullscreen mode Exit fullscreen mode

output

denomiator cannot be zero
please retry
Enter fullscreen mode Exit fullscreen mode

beeter way [throwing error]

using error constructor

throw new Error(message,options)
Enter fullscreen mode Exit fullscreen mode
throw new Error('denominator cannot be zero ${name}')
Enter fullscreen mode Exit fullscreen mode

đź”—linkedin

learning resources

🧡Scaler - India's Leading software E-learning
🧡w3schools - for web developers

Top comments (0)