Глава 34: вычитывание

This commit is contained in:
Igor Simdyanov
2022-05-24 15:55:33 +03:00
parent 3267fb7613
commit 6b5018b5ce
7 changed files with 63 additions and 2 deletions

View File

@ -0,0 +1,22 @@
<?php
require_once 'interfaces.php';
// Ошибка: файл не найден
class FileNotFoundException extends Exception
implements IFileException {}
// Ошибка: ошибка доступа к сокету
class SocketException extends Exception
implements INetException {}
// Ошибка: неправильный пароль пользователя.
class WrongPassException extends Exception
implements IUserException {}
// Ошибка: невозможно записать данные на сетевой принтер
class NetPrinterWriteException extends Exception
implements IFileException, INetException {}
// Ошибка: невозможно соединиться с SQL-сервером
class SqlConnectException extends Exception
implements IInternalException, IUserException {}

View File

@ -0,0 +1,6 @@
<?php
interface IException {}
interface IInternalException extends IException {}
interface IFileException extends IInternalException {}
interface INetException extends IInternalException {}
interface IUserException extends IException {}

21
exceptions/iface/test.php Normal file
View File

@ -0,0 +1,21 @@
<?php
require_once 'exceptions.php';
try {
printDocument();
} catch (IFileException $e) {
// Перехватываем только файловые исключения
echo "Файловая ошибка: {$e->getMessage()}.<br />";
} catch (Exception $e) {
// Перехват всех остальных исключений
echo 'Неизвестное исключение: <pre>', $e, '</pre>';
}
function printDocument()
{
$printer = '//./printer';
// Генерируем исключение типов IFileException и INetException
if (!file_exists($printer)) {
throw new NetPrinterWriteException($printer);
}
}

View File

@ -13,7 +13,7 @@ try {
}
catch(Exception $exp)
{
echo 'Exception-исключение ' . get_class($exp) . '<br />';
echo 'Exception-исключение ' . $exp::class . '<br />';
// Передача исключения далее по каскаду
throw $exp;
}

View File

@ -12,7 +12,7 @@ try {
}
catch(Exception $exp)
{
echo 'ExceptionSQL-исключение ' . get_class($exp) . '<br />';
echo 'ExceptionSQL-исключение ' . $exp::class . '<br />';
// Передача исключения далее по каскаду
throw $exp;
}

10
exceptions/tostring.php Normal file
View File

@ -0,0 +1,10 @@
<?php
function test($n)
{
$e = new Exception("bang-bang #$n!");
echo '<pre>', $e, '</pre>';
}
function outer() { test(101); }
outer();

View File

@ -23,6 +23,7 @@ class User
throw new AttributeException($index);
}
}
public function __set(string $index, string $value) : void
{
if (isset($this->$index)) {
@ -32,6 +33,7 @@ class User
throw new AttributeException($index);
}
}
public function isPasswordCorrect($password)
{
return $this->password == $password;