30
loading...
This website collects cookies to deliver better user experience
//such is allowed in Javascript
const x = false * "jamie"
//this gives an output of NaN. that can bubble through our //programs until it encounters an operation that makes our //program blow up
function spotTheError(){
"use strict"
for ( counter=0; counter < 10; counter++){
console.log("hello" , counter)
}
}
//run the function
spotTheError
//sample code example
function whatIsThis(){
"use strict"
console.log(this)
}
function whatIsThisTwo(){
console.log(this)
}
//constructor function
function Person(name) { this.name = name }
const Jamie = Person("Jamie"); //oops forgot the new keyword
console.log(name);
//jamie
"use strict"
function Person(name) { this.name = name }
const Jamie = Person("Jamie"); //oops forgot the new keyword
//TypeError caannot set property 'name' of undefined.
function howOld( age ){
if ( age < 30 ) return "Gen Z";
if ( age > 30 ) return "Agbalagba";
throw new Error("invalid age : ",age );
}
function lookUpAge(){
if ( howOld(34) ==== "Gen Z"){
return "Twitter"
}else{
return "Facebook"
}
}
try{
lookUpage()
} catch(error){
console.log("something went wrong");
}
try{
} catch(e){
} finally{
//this blocks get called no matter what
}
//code showing generic error catching
function cookDinner(){
const ingredients = prompt("what are you cooking");
if ( ingredients ==== "spice" ) return "jollof rice"
if ( ingredients === "stew" ) return "white rice"
throw new Error(`Invalid ingredients: ${ingredients}`)
}
//running our function and catching any exception
try {
let result = cookDinner();
if ( result ) return;
} catch (e){
//exception caught
console.log("your ingredient is wrong");
}
class InputError extends Error {
constructor(message){
super();
this.message = message;
}
}
This InputError will be thrown inside our cookFood function instead of the standard Javascript Error Object.
function cookDinner(){
const ingredients = prompt("what are you cooking");
if ( ingredients ==== "spice" ) return "jollof rice"
if ( ingredients === "stew" ) return "white rice"
//replace the below line
throw new Error(`Invalid ingredients: ${ingredients}`)
//with the InputError class
throw new InputError(`Invalid ingredients: ${ingredients}`);
}
//then we can look out for our InputError in the catch block
try {
let result = cookDinner();
if ( result ) return;
} catch (e){
//exception caught
if ( e instanceof InputError ) {
//do something with Input Error here
}
//we can still throw our original exception
else {
throw e
}
}