• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

PHP Advanced PHP :: Exceptions

Paxton

Banned User
Joined
Feb 23, 2008
Messages
4,110
Reaction score
48
Location
London, UK
Hello

In todays tutorial we will be talking about feature that provides PHP which is 'Exception'.

Maybe you have seen this feature in POT classes, and a lot of fatal errors in Gesior ACC caused by uncaught exceptions. :blink:

We will not be talking in advanced of advanced exception because mostly in practise it is not needed.

If you know basic OOP in PHP then you will understand structure of exception because this actually is a class.

Okey, let's start shall we?

Imagine you got a class, which connects and select database.

PHP:
<?php
//We declare new class 'database'
class database() {
          //We are declaring 'starting' function
		  
		  function __construct($dbhost, $dblogin, $dbpass, $dbname){
			//Try to connect to database
			if(mysql_connect($dbohst, $dblogin, $dbpass))
				return true;
			else
				return false;
				
			//Try to select database.
			
			if(mysql_select_db($dbname))
				return true;
			else
				return false;
		  }


}

?>

Okey, so in this case when we pass bad data as arguments to this class, we will not know if we passed bad arguments for connecting to database or bad info about name of database because both returns same thing, false.

I know we might just write other method for each action, but this was just example, couldn't find better.

So here for help comes exceptions!

Exception is an object so we crate them same as classes, let's put exceptions into that code.

PHP:
<?php
//We declare new class 'database'
class database() {
          //We are declaring 'starting' function
		  
		  function __construct($dbhost, $dblogin, $dbpass, $dbname){
			//Try to connect to database
			if(mysql_connect($dbohst, $dblogin, $dbpass))
				return true;
			else
				throw new exception("Could not connect to database.");
				
			//Try to select database.
			
			if(mysql_select_db($dbname))
				return true;
			else
				throw new exception("Could not select database.");
		  }


}

?>

Here I'm throwing exceptions, but beware! If I will not catch them then I will get nasty fatal error.

How to use it now then?

PHP:
try {

	$db = new database('localhost', 'root', 'password', 'myDataBase');
}
catch(exception $myEx) {
	echo $myEx->getMessage();
}

Alright, what does it do?

We are declaring new object which is class ('database') which we wrote before, and we pass the right arguments to it, but what if they are not right? Exception will be thrown and the next code tries to catch it, and create object $myEx which is my own variable, you can change it to whatever you want (Must be correct variable).

PHP:
getMessage();

Is own exception method which will return the message we wrote while throwing exception for example: 'Could not connect to database.'

And we echo this, so the message will be shown.

There is few more methods for exceptions here are the list from php.net

PHP:
Exception::__construct — Construct the exception
Exception::getMessage — Gets the Exception message
Exception::getPrevious — Returns previous Exception
Exception::getCode — Gets the Exception code
Exception::getFile — Gets the file in which the exception occurred
Exception::getLine — Gets the line in which the exception occurred
Exception::getTrace — Gets the stack trace
Exception::getTraceAsString — Gets the stack trace as a string
Exception::__toString — String representation of the exception
Exception::__clone — Clone the exception

But this is not end!

What if I not catch exception, I don't want this nasty fatal error!

So you can write function which will be fired for this fatal error, Why did Gesior didn't do it? :blink:

PHP:
set_exception_handler('unCaught');

function unCaught() {
    echo "I did not catch the exception =(";
}

The argument here:

PHP:
set_exception_handler('unCaught');

Which is unCaught is name of a function which will be fired when exception is not caught, and the Fatal Error will not be shown.

Good idea if you don't want your users to see those nasty error is to create functions which will display error saying the website is currently down and use function exit!

Alright, I hope you understand! :)

PRACTISE PRACTISE PRACTISE!

I did not test the PHP code, I wrote it just now so if there is some mistake in code/tutorial then write it here :)

Feedback please.
 
Okay, here is feedback:
1. Dont use mysql_* functions.
2. You can actually extend the class with MySQLi class (class database extends MySQLi) or use already started connection (if any):
PHP:
$connection = new MySQLi('host', 'user', 'pass', 'db');
class database
{
    private $db = NULL;
    public function __construct($connection)
    {
        if($connection) then
        {
            $this->db = $connection;
            return true;
        }
        else
            return false;
    }

    function exampleQuery()
    {
        $this->db->query("SELECT * FROM `table`;");
    }
}
Declaring connection now ->
PHP:
$db = new database($connection);
3. "Advanced PHP :: Exceptions", not really :S
4. In your script connection is not closed, use __destruct:
PHP:
public function __destruct()
{
    mysql_close();
}
 
Last edited:
Okay, here is feedback:
1. Dont use mysql_* functions.
2. You can already extend the class with MySQLi class (class database extends MySQLi)
3. "Advanced PHP :: Exceptions", not really :S

The class was just an example.

And don't tell me throwing Exceptions you will find in baisc PHP tutorial, because I'v enever seen it, it might not be advanced for people that actually are in PHP for few years.
 
I thinks this 'example' will be too hard for begginers, who don't know how to use simple variables, like in tutorials you made before. :(
 
I thinks this 'example' will be too hard for begginers, who don't know how to use simple variables, like in tutorials you made before. :(

That's why I did title which says ADVANCED :wub:

If you try to learn what is exception you need to know basic OOP.
 

Similar threads

Back
Top