PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] What do we need the PHP-exception code for? Any use case scenario?

 August 04, 2022     exception, exception-handling, php     No comments   

Issue

Okay, its a very lame question for many but I hope I will have overwhelming response :)

When I throw an Exception in PHP I can add a code to the message.
I catch an exception and handle it according to its type (Like InvalidArgumentException or OutOfBoundException). I log the message or display it or do whatever is suitable.
I can add also append a previous exception to trace a path to the origin of the error.

BUT one thing I have never used or never thought of: how useful is code?

For example:

throw new Exception("db Error", $code, $previousException);

What do I do with $code?


Solution

The message is for display to the user, while the code is for use by your program. So for example, in your "database error" example, you might make up a set of codes like

  1. Can't connect
  2. Error during query
  3. Empty result
  4. Error closing connection

and then use the appropriate code. Then when other parts of your code saw they exception, they would know what happened and could possibly deal with it intelligently.



Answered By - Ernest Friedman-Hill
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing