Handling exceptions

Objectives

Try, throw, catch

// example of code that throws exceptions function add(a, b) { if (arguments.length != 2) { throw "Invalid number of arguments"; } if (typeof a != 'number' || typeof b != 'number') { throw "Illegal argument exception"; } if (!isFinite(a) || !isFinite(b)) { throw "Illegal number exception"; } return a + b; } // this will display: Invalid number of arguments try { console.log(add()); } catch (err) { console.log(err); } // this will display: Illegal argument exception try { console.log(add("1", "2")); } catch (err) { console.log(err); } // this will display: 7 try { console.log(add(3, 4)); } catch (err) { console.log(err); } // this will display: Invalid number of arguments try { console.log(add(1,2,3)); } catch (err) { console.log(err); } // this will display: Illegal number exception try { console.log(add(5/0,3)); } catch (err) { console.log(err); } // this will display: Illegal argument exception try { console.log(add(5,"2")); } catch (err) { console.log(err); }

Using assert

// example of code that throws exceptions function add(a, b) { console.assert(arguments.length==2, "Invalid number of arguments"); console.assert(typeof a == 'number' && typeof b == 'number', "Illegal argument exception"); console.assert(isFinite(a) && isFinite(b), "Illegal number exception"); return a + b; } console.log(add()); // displays: Invalid number of arguments console.log(add("1", "2")); // displays: Illegal argument exception console.log(add(3, 4)); // displays: 7 console.log(add(1,2,3)); // displays: Invalid number of arguments console.log(add(5/0,3)); // displays: Illegal number exception console.log(add(5,"2")); // displays: Illegal argument exception