DEV Community

aryan015
aryan015

Posted on • Edited on

Error handling in JS🤣

❤

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more