Q:

try catch finally in javascript

try {
  // Try to run this code 
}
catch(err) {
  // if any error, Code throws the error
}
finally {
  // Always run this code regardless of error or not
  //this block is optional
}
24
var someNumber = 1;
try {
  someNumber.replace("-",""); //You can't replace a int
} catch(err) {
 console.log(err);
}
22
try {
  // Try to run this code
}
catch(err) {
  // Code throws error
}
finally {
  // Always run this code regardless of error or not
}
2
"The try...catch statement marks a block of statements to try and specifies"
"a response should an exception be thrown."

try {
  nonExistentFunction();
} catch (error) {
  console.error(error);
  // expected output: ReferenceError: nonExistentFunction is not defined
  // Note - error messages will vary depending on browser
}
0
<html>  
<head>Exception Handling</head>  
<body>  
<script>  
try {  
   throw new Error('This is the throw keyword'); //user-defined throw statement.  
}  
catch (e) {  
  document.write(e.message); // This will generate an error message  
}  
</script>  
</body>  
</html>  
0
try {

  alert('Start of try runs');  // (1) <--

  lalala; // error, variable is not defined!

  alert('End of try (never reached)');  // (2)

} catch(err) {

  alert(`Error has occurred!`); // (3) <--

}
0
try {
  alert( 'try' );
  if (confirm('Make an error?')) BAD_CODE();
} catch (e) {
  alert( 'catch' );
} finally {
  alert( 'finally' );
}
0

 <p id="demo"></p>

<script>

try {
  adddlert("Welcome guest!");
}
catch(err) {
  
document.getElementById("demo").innerHTML = err.message;
}
</script> 
-1

New to Communities?

Join the community