• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Handing errors in my code using Exceptions

(09-22-2015, 10:03 AM)jLinux Wrote: I think you think that I plan on using exceptions to basically generate every error message or notification (Which if thats how I came across, then I apologize). I really only plan on using it for serious issues, such as when an error in a lib/model was encountered that should terminate the execution of the model.

Edit: Hm, that does mean that I would have to catch the exception in the models as well, if its relying on a method that throws exceptions

It doesn't really matter whether you use exceptions for every error or only for those which should terminate execution. In most object-oriented languages, it would be very common to throw exceptions for every error. The ErrorException type which you used in your original example just happens to have been created for the purposes of converting errors into Exceptions.

My main point is that when you catch the exception, you usually try to determine in the catch block whether you will continue, throw another exception, or terminate execution. If you don't catch the exception, it moves on to the calling code or, if the calling code doesn't catch it, to the application's exception handler (and though this wouldn't usually be the case for CI, if an exception handler isn't set it goes to PHP and terminates anyway).

In some languages (not in PHP), you can specify separate catch blocks for different types of Exceptions. In PHP, you can do this with nested try/catch statements or by catching a base Exception and using conditional statements in the catch block to determine the exact type. It's more painful than it should be, but we take what we can get. This means it's harder to give you an example of why it's a good idea to throw specific Exception types for specific things, because the example wouldn't look that much different from what you already have. However, one basic example is that you can be specific about which types of Exceptions you catch, then all other types of Exception will blow through your catch block and up to the higher level code until something does catch it, so you don't end up trying to handle an unexpected Exception in the same manner as the Exceptions you explicitly threw.

All I'm trying to say is that when you throw an Exception, the type of Exception thrown is important if, for one reason or another, you don't catch the Exception. If you do catch it, the only reason it's going to matter is for long-term maintenance, or when you catch something you didn't intend to catch in the first place.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.