Jump to content

Custom Exception


terryds

Recommended Posts

How to make a custom exception class ?

 

<?php
class MyPDOException extends Exception {
public function __construct($msg, $code=NULL) {
$err = $msg;
if (isset($code)) {
$err .= " Error code: " . $code;
}
return $err;
}
try {
throw new MyPDOException('aaaa');
}
catch (MyPDOException $e) {
echo $e->getMessage();
}
But, when the script is execute, it gives me a blank page, not 'aaaa' .... Can you tell me how to make custom exceptions so it can work properly?
Link to comment
Share on other sites

it doesn't look like getMessage() is a method of your class.

 

maybe try

class MyPDOException extends Exception {private $err;public function __construct($msg, $code=NULL) {$this->err = $msg;if (isset($code)) {$this->err .= " Error code: " . $code;} public function getMessage() { return $this->err; }}

edit: nevermind, I just now saw that you are extending the Exception class

 

maybe this:

class MyPDOException extends Exception {public function __construct($msg, $code=NULL) {parent::err = $msg;if (isset($code)) {parent::err .= " Error code: " . $code;} public function getMessage() { return parent::getMessage();  }}
Edited by astralaaron
Link to comment
Share on other sites

Just call the parent's constructor

class MyPDOException extends Exception {    public function __construct($msg, $code=NULL) {        parent::__construct($msg, $code);    }}

Here's the PHP manual's explanation: http://es1.php.net/manual/en/language.exceptions.extending.php

  • Like 1
Link to comment
Share on other sites

Umm... But, the code didn't work as what i want, it gives me 'aaaa' not as what i want :

 

<?php
class MyPDOException extends Exception {
public function __construct($msg, $code=0) {
parent::__construct($msg, $code);
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}";
}
}
try {
throw new MyPDOException('aaaa',2013);
}
catch (MyPDOException $e) {
echo $e->getMessage();
}
Can you tell me how to make it work so i can throw MyPDOException : [2013] : aaaa ?
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...