Showing posts with label throw. Show all posts
Showing posts with label throw. Show all posts

Javascript: Custom exceptions

In Javascript custom exception can be created and make them caught by `catch`.
For example lets see below code

let json = '{ "age": 30 }'; // incomplete data
try {
  let user = JSON.parse(json);  
  if (!user.name) {
    throw new Error("Incomplete data: no name"); 
  }
  alert( user.name );
} catch (err) {
  alert( "JSON Error: " + err.message ); // JSON Error: Incomplete data: no name
}
Hope it helps.
Thank you.