Does it necessary using sef-defined Exception - php

As we all konwn,PHP have a class named "Exception"to handle the unexcepting situation.I usually find that someone like self-define a new exception class which extend the class "Exception". This new exception class do not rewrite or add any function.It just state a children class of the class "Exception".
so,I doubt that if it is necessary self-define a new Exception class in my project?In the past,I used the class "Exception" in anywhere.

It is not necessary, but it might be very convenient: If you have different kinds of exceptions, you can handle them differently when you catch them:
try {
...
} catch (SpecificException $e) {
// Do something specific here
} catch (SomeOtherException $e) {
// Here you can do something else
} catch (\Exception $e) {
// The rest...
}

The main reason to define an exception in that way is to help with debugging and error handling. Not only is something like NetworkException more informative, but you can also catch that type of exception when it occurs, so you can deal with different types of exceptions in different ways. Some may be temporary, so you might catch them and ask the user to try again later, for instance.

Related

How to catch an Exception that is chain called into multiple Classes PHP

Suppose I have a repository class, a service class, and finally a controller class.
Now, I have a repository class that uses PDO, and I enclosed the execution into a try-catch block, example, below:
MyRepository {
public function someRepositoryFunction()
{
try {
...some pdo execution
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
}
My question is, when I call that someRepositoryFunction() in the Service class, do I have to enclose it in a try-catch block also? example, below:
MyService {
public function someServiceFunction()
{
$repo = new MyRepository();
try {
$repo->someRepositoryFunction();
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
}
and finally, when I call the Service class in the Controller, do I also have to enclose the someServiceFunction() in a try-catch block?
Or, catching it in the Repository class enough?
When you catch an Exception, you got 2 options, manage the Exception right were you caught it, according to your app logic or needs or you can throw the exception again and propagate this Exception.
In your case you are throwing the exception again, so you need to catch it again in whatever place you called the method and if you keep throwing the exception up you have to keep catching it.

How to find out what the exact Throwable class is?

I have a try/catch block where I catch all Throwable exceptions.
try {
...
} catch (Throwable $ex) {
...
}
How do I, at runtime, figure out what the exact class of the throw exception is? I want to add multiple catch blocks to handle different exceptions differently, but am unable to find out the types of exceptions that are thrown.
Try to dump get_class($ex) inside your catch block. It will give you the class name of $ex.
After the class name is found, you can use catch with exact class exception.

Easy way to list all of exceptions "try" block may produce

Is there any easy way to find out, which types of exception I can expect in try block? Let's say I have:
<?php
try {
foo();
} catch (\A\B\FooException $e) {
} catch (\A\B\BarException $e) {
}
Is there any tool which can inspect the foo() code for me and list all of exceptions types I can expect there? So if there is \A\B\BazException I forgot, I can easily add another catch thanks to that list. For now I use search for "Exception", but sometimes there is to many the same results.
I don´t know any tools to do that. But you can create at least the code block below:
catch (Exception $e) {
mysql_query("INSERT INTO exceptions_tb ('exception_name','expection_message') VALUES ('"+$e->class+"', '"+addslashes($e->message)+"') excetption ", $conn);
}
And after consult the variations of exceptions happened in all your unit tests. Or simply you can do all possible ways and input data types in your unit tests and see what exceptions will arise.
I don´t believe there is a tool that can do this for you also because the tool will need to now all possible inputs and php variables are not predefined types.
...
catch (Exception $oError) {
Logger::logError($oError);
}
class Logger
{
public static function($oError){
// do here detection you like\want
// you can use loops and pre-def. instances of errors
if ($oError instanceof ExceptionCustom)
// some actions
}
...
}
}
class ExceptionCustom extends Exception {
// http://www.php.net/manual/en/language.exceptions.extending.php
//...
}
It's only sample, base thing. You can\should do it more complicated the way you want.
ADDED:
Main thing that you will decide, what error and what you should do, only after you receive exception, and of course you should create default action for it (no matter what exception is thrown).

Should the Exception Class always be caught in try catch?

Is it good coding practice to always catch the base Exception class in a try catch?
try
{
//
// Piece of code
//
}
catch (CustomException $my_ex)
{
// Handle CustomExcepton
}
catch (Exception $other_exceptions)
{
// Handle all other exceptions
}
If so, why?
In PHP you can install a global exception handler.
When needed you can catch exceptions in your code, all unhandled exceptions go to the global exception handler. Depending on your strategie, you decide what to do.
Of course, when you decide to die, a clear error message and a log is appreciated.
In general, if you can recover from a exception, use a try .. catch block, otherwise let the global exception handler do his work, and do not recover.
You should catch only exceptions you now how to handle. Others should bubble up to calling method and some global handler in the end.

What is the point of using custom exception class in php?

In some libraries it is common practice to make custom Exception classes for every error condition, like:
class FileNotFound_Exception extends Exception {}
You can handle certain type of Exception, however you cannot read all source code of all libraries to remember each Exception class, and cannot take full advantage of using custom Exceptions. Most of time I just catching them with base Exception class:
catch (Exception $e)
{
// log and display friendly error
}
Is there other ways to have benefit of custom Exception classes, without writing long list of catch blocks?
I like Exceptions, but don't know how to use them properly. Thank you.
The benefit of having your own Exception class is that you, as the author of the library, can catch it and handle it.
try {
if(somethingBadHappens) {
throw MyCustomException('msg',0)
}
} catch (MyCustomException $e) {
if(IcanHandleIt) {
handleMyCustomException($e);
} else {
//InvalidArgumentException is used here as an example of 'common' exception
throw new InvalidArgumentException('I couldnt handle this!',1,$e);
}
}
Well, custom exception classes lets you route your errors properly for better handling.
if you have a class
class Known_Exception extends Exception {}
and a try catch block like this:
try {
// something known to break
} catch (Known_Exception $e) {
// handle known exception
} catch (Exception $e) {
// Handle unknown exception
}
Then you know that Exception $e is an unknown error situation and can handle that accordingly, and that is pretty useful to me.

Categories