An exception is an object that describes an error or unexpected behavior of a PHP script. Exceptions are used to change the normal flow of a code execution if a specified error condition occurs.
To handle exceptions, we wrap our code in a try block. If an error occurs, the code execution jumps to the catch block.
The throw statement allows a user-defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed.
The finally block can be used after or instead of catch blocks. Code inside the finally block will always run, regardless of whether an exception was thrown or caught.
When an exception is caught, you get an Exception Object which contains useful information about the error:
getMessage(): Returns a string describing the exception.getCode(): Returns the exception code.getFile(): Returns the full path of the file where the exception occurred.getLine(): Returns the line number where the exception occurred.You can create your own exception classes by extending the built-in Exception class to handle specific types of errors in your application.
if...else statements are usually better.