HTML and CSS Reference
In-Depth Information
type: "pointless_exception",
code: 1000
If you want to see what type of exception has been thrown, it's usually better to
throw an object. As you can see from the preceding code, you can put pretty
much anything in there, including a code, type, and a message. If you were to
throw a primitive type exception (string, Boolean, integer), nobody other than
you will probably be able to figure out what the exception was, what it meant,
and most importantly, how to handle it. By using an object, you have the ability
to check against a code or type, rather than trying to compare a complex string.
The next step is to catch the exception after it's been thrown. This is a simple
task. To test this out, you can wrap your conditional statement in a function and
call it from the try / catch block, just to show you how it would work in a real-
world situation.
function doSomething(){
if(true !== false){
throw {
message: "True definitely isn't equal to false",
type: "pointless_exception",
code: 1000
try {
} catch (e){
If you try out this code, you'll find that the exception is thrown, and e.message
will retrieve the message for you and alert it.
It's important to understand that exceptions should be used only when there is
no other way to handle the error in your block of code.
The next section will take you through hardening the models so that the setters
will throw exceptions if the wrong type of value is passed to them. The getters
have been omitted to make it easier to read.
Strengthening the Models
The new validation rules (shown in bold in the following code) simply check the
type. If the value is not of a certain type, it will throw a validation exception and
Search WWH ::

Custom Search