diff --git a/assets/templates/_table_of_contents.phtml b/assets/templates/_table_of_contents.phtml index dfea08e..9ce3436 100644 --- a/assets/templates/_table_of_contents.phtml +++ b/assets/templates/_table_of_contents.phtml @@ -22,6 +22,7 @@
  • Static
  • Interfaces
  • Abstract Classes
  • +
  • Exceptions
  • Credits diff --git a/code/exceptions.php b/code/exceptions.php new file mode 100644 index 0000000..6548bfe --- /dev/null +++ b/code/exceptions.php @@ -0,0 +1,60 @@ +getNumber()) !== 16) { + throw new Exception('Credit card is not right'); + } + } +} + +// In this case, if someone tried to use the Processor class +// to charge a credit card number that is not 16 characters long, an +// exception will be thrown which stops the rest of the code from running. +$processor = new Processor(); +$processor->charge('1234'); + +// A developer who wants to prevent an exception from stopping code execution +// can catch the exception and use it for logging or a return an error to a user. + +// Just wrap the code that might throw an exception with the keyword "try" and brackets +// followed by "catch", the exception type in parentheses and more brackets. +try { + $processor->charge('1234'); +} catch (Exception $e) { + echo $e->getMessage() . "\n"; +} + +// You can make your own custom exceptions as well. They are just classes +// that extend Exception. +class MyCustomException extends Exception {} + +// Then, you can try to catch your exception instead of the base exception. +try { + throw new MyCustomException('I am a custom exception'); +} catch (MyCustomException $e) { + echo "Cauth MyCustomException\n"; +} + +// Since all exceptions inherit from Exception, catching +// Exception will catch any and all exceptions that might be thrown. +try { + throw new MyCustomException('I inherit from Exception'); +} catch (Exception $e) { + echo "Still caught MyCustomException\n"; +} + +// You can also create multiple catch blocks to handle different types of exceptions in +// one try-catch. +try { + throw new MyCustomException('I am being thrown again'); +} catch (MyCustomException $e) { + echo "MyCustomException was caught\n"; +} catch (Exception $e) { + echo "Just in case a different exception is thrown\n"; +} diff --git a/config.php b/config.php index 60ebd86..e1b41b8 100644 --- a/config.php +++ b/config.php @@ -146,7 +146,13 @@ return [ Page::create('abstract', null, 'abstract.php', [ 'title' => 'Abstract Classes', 'subtitle' => 'Inheriting an interface', - 'previous' => 'interfaces', + 'previous' => 'interface', + 'next' => 'exceptions', + ]), + Page::create('exceptions', null, 'exceptions.php', [ + 'title' => 'Exceptions', + 'subtitle' => 'Throwing errors', + 'previous' => 'abstract', 'next' => '', ]), ],