chinmay.sahoo
New member
When writing scripts, it’s normal practice to test the type of data passed to a function. This often results in complex conditional statements that determine what should happen if the data is of the wrong type. The advantage of using exceptions is that it reduces complexity by handling what should be done in a separate part of the script. This is particularly important with OOP, because classes should be designed to be as project neutral as possible. So, when a problem arises with data passed to a method, keep things simple by throwing an exception inside the method, and leave it to the main application script to determine how to handle it.
The way you throw an exception is with the throw keyword like this:
Following the throw keyword, you instantiate a new Exception object, which takes one argument: a string that identifies the nature of the problem. Technically speaking, this argument is optional; if you omit it, PHP uses the default value, “Unknown exception.” You can also pass a number as an optional second argument. The number has no significance other than to identify the exception. This allows you to set up your own system of error codes.
The way you throw an exception is with the throw keyword like this:
if (the sky falls in) {
throw new Exception('Oops, the sky has fallen in!');
}
Following the throw keyword, you instantiate a new Exception object, which takes one argument: a string that identifies the nature of the problem. Technically speaking, this argument is optional; if you omit it, PHP uses the default value, “Unknown exception.” You can also pass a number as an optional second argument. The number has no significance other than to identify the exception. This allows you to set up your own system of error codes.