0
0
PHPprogramming~10 mins

Custom exception classes in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a custom exception class named MyException.

PHP
<?php
class MyException extends [1] {
}
?>
Drag options to blanks, or click blank then click option'
ARuntimeException
BError
CThrowable
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Extending a class that is not an exception base class.
Forgetting to extend any class.
2fill in blank
medium

Complete the code to throw a custom exception named MyException with the message 'Error occurred'.

PHP
<?php
throw new [1]('Error occurred');
?>
Drag options to blanks, or click blank then click option'
AMyException
BError
CException
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing the base Exception instead of the custom one.
Using a class name that does not exist.
3fill in blank
hard

Fix the error in the code to catch the custom exception MyException.

PHP
<?php
try {
    // some code
} catch ([1] $e) {
    echo $e->getMessage();
}
?>
Drag options to blanks, or click blank then click option'
AMyException
BError
CException
DThrowable
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the base Exception instead of the custom one.
Using a wrong class name in catch.
4fill in blank
hard

Fill both blanks to define a custom exception class with a constructor that sets a default message.

PHP
<?php
class MyException extends [1] {
    public function __construct() {
        parent::[2]('Default error message');
    }
}
?>
Drag options to blanks, or click blank then click option'
AException
BError
C__construct
Dthrow
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parent class.
Calling a method other than __construct.
5fill in blank
hard

Fill all three blanks to throw and catch a custom exception, then print its message.

PHP
<?php
class MyException extends Exception {}

try {
    throw new [1]('Custom error');
} catch ([2] $e) {
    echo [3];
}
?>
Drag options to blanks, or click blank then click option'
AException
BMyException
C$e->getMessage()
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Throwing and catching different exception classes.
Printing the exception variable directly instead of calling getMessage().