Exception : an ugly grammer in programming

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Yarco

    Exception : an ugly grammer in programming

    Well, friend. Yes, I'm doing PHP. But exception is a traditional
    machinism in programming languages. I'm very doubt about this.
    In procedure language, we return error code when we meet an error. So
    we need to design error code table and judge them in several
    statements. Finally they become boring.
    But how about use exception in OOP? Did we drop all "return error
    code" styles?
    If i want to fetch a webpage:

    <?php
    function fetchPage($url)
    {
    //...do something

    //if the net speed is very slow, cause we can't fetch the page
    throw new SlowNetSpeed("p age can't be getted");

    //if the page is moved
    throw new NoPage("page does't exist");

    //...do something
    }

    // so what can i do, if i want the fetchPage procedure go on fetching
    when SlowNetSpeed Exception happen?
    // it stop when NoPage Exception happen?
    while (1)
    {
    try
    {
    $c = fetchPage('Some _Where');
    // do something
    break;
    }
    catch (SlowNetSpeed $e)
    {
    }
    catch(NoPage $e)
    {
    break;
    }
    }
    ?>
    It is very ugly if there exists more Exceptions and other procedure.

    Then i'm missing "return error code" style. But i know "return error
    code" is not a good method when we deal with error. And exception is
    also an ugly grammer when we want to keep code clean.

  • Willem Bogaerts

    #2
    Re: Exception : an ugly grammer in programming

    Well, friend. Yes, I'm doing PHP. But exception is a traditional
    machinism in programming languages. I'm very doubt about this.
    In procedure language, we return error code when we meet an error. So
    we need to design error code table and judge them in several
    statements. Finally they become boring.
    But how about use exception in OOP? Did we drop all "return error
    code" styles?
    <snip>
    // so what can i do, if i want the fetchPage procedure go on fetching
    when SlowNetSpeed Exception happen?
    I think you'll have to decide. Is it something that can be repaired from
    outside the object? if so, you can throw an exception. Is it not broken
    at all? Then it is not an exception. You could implement an event
    mechanism (java style) to handle this events and just continue fetching.

    The way I see it, it is the responsibility of the fetcher class to fetch
    the page and inform the user if it can take a while. Not being able to
    perform that task is an exception, but a slow connection is not.

    So I would do something like:

    class ConnectionNotif ier
    {public function NotifySlowConne ction()
    {echo 'Please have patience. It is rather busy at the moment.';}
    }

    class PageFetcher
    {private $_slowConnectio nWarner;
    public function __construct(Con nectionNotifier $slowConnection Warner)
    {$this->_slowConnectio nWarner = $slowConnection Warner;}
    public function FetchPage($URL)
    {$connection = ... // establish a connection here
    if(! $connection):
    throw new NoPageException ();
    endif;
    // if you notice a slow connection, withing a fetching loop:
    $this->_slowConnectio nWarner->NotifySlowConn ection();
    }
    }

    Off course, you would add code to make sure there is only one
    notification, but you could do that in the ConnectionNotif ier class to
    keep the code clean.

    Best regards,
    --
    Willem Bogaerts

    Application smith
    Kratz B.V.

    Comment

    • Mindaugas.Liubinas@gmail.com

      #3
      Re: Exception : an ugly grammer in programming

      Did you consider using custom error handler? You will be able to call
      it with trigger_error function with custom error levels, plus you can
      control where the error message goes (email, log, etc.) Here's an ugly
      example:

      <?php
      // set the user error handler method to be hl_error_handle r
      set_error_handl er("hls_error_h andler", E_ALL);
      // error handler function
      function hls_error_handl er($errNo, $errStr, $errFile, $errLine)
      {
      /* the first two elements of the backtrace array are irrelevant:
      -DBG_Backtrace
      -outErrorHandler */
      $backtrace = dbg_get_backtra ce(2);
      // error message to be displayed, logged or mailed
      $error_message = "\nERRNO: $errNo \nTEXT: " . $errStr . " \n" .
      "LOCATION: " . $errFile . ", line " . $errLine . ", at
      " .
      date("F j, Y, g:i a") . "\nShowing backtrace:\n" .
      $backtrace . "\n\n";
      // email the error details, in case SEND_ERROR_MAIL is true
      if (SEND_ERROR_MAI L == true)
      error_log($erro r_message, 1, ADMIN_ERROR_MAI L, "From: " .
      SENDMAIL_FROM . "\r\nTo: " . ADMIN_ERROR_MAI L);
      // log the error, in case LOG_ERRORS is true
      if (LOG_ERRORS == true)
      error_log($erro r_message, 3, LOG_ERRORS_FILE );
      // warnings don't abort execution if IS_WARNING_FATA L is false
      // E_NOTICE and E_USER_NOTICE errors don't abort execution
      if (($errNo == E_WARNING && IS_WARNING_FATA L == false) ||
      ($errNo == E_NOTICE || $errNo == E_USER_NOTICE))
      // if the error is non-fatal ...
      {
      // show message only if DEBUGGING is true
      if (DEBUGGING == true)
      echo "<pre>" . $error_message . "</pre>";
      }
      else
      // if error is fatal ...
      {
      // show error message
      if (DEBUGGING == true)
      echo "<pre>" . $error_message . "</pre>";
      else
      echo SITE_GENERIC_ER ROR_MESSAGE;
      // stop processing the request
      exit;
      }
      }
      // builds backtrace message
      function dbg_get_backtra ce($irrelevantF irstEntries)
      {
      $s = '';
      $MAXSTRLEN = 64;
      $traceArr = debug_backtrace ();
      for ($i = 0; $i < $irrelevantFirs tEntries; $i++)
      array_shift($tr aceArr);
      $tabs = sizeof($traceAr r) - 1;
      foreach($traceA rr as $arr)
      {
      $tabs -= 1;
      if (isset($arr['class']))
      $s .= $arr['class'] . '.';
      $args = array();
      if (!empty($arr['args']))
      foreach($arr['args']as $v)
      {
      if (is_null($v))
      $args[] = 'null';
      else if (is_array($v))
      $args[] = 'Array[' . sizeof($v).']';
      else if (is_object($v))
      $args[] = 'Object:' . get_class($v);
      else if (is_bool($v))
      $args[] = $v ? 'true' : 'false';
      else
      {
      $v = (string)@$v;
      $str = htmlspecialchar s(substr($v, 0, $MAXSTRLEN));
      if (strlen($v) $MAXSTRLEN)
      $str .= '...';
      $args[] = "\"" . $str . "\"";
      }
      }
      $s .= $arr['function'] . '(' . implode(', ', $args) . ')';
      $Line = (isset($arr['line']) ? $arr['line']: "unknown");
      $File = (isset($arr['file']) ? $arr['file']: "unknown");
      $s .= sprintf(" # line %4d, file: %s", $Line, $File, $File);
      $s .= "\n";
      }
      return $s;
      }
      ?>

      There are some constants in this example, but they quite self-
      explanatory. Function dbg_get_backtra ce is dedicated for user-friendly
      output and trace. Hope this helps a bit

      Comment

      • Jerry Stuckle

        #4
        Re: Exception : an ugly grammer in programming

        Yarco wrote:
        Well, friend. Yes, I'm doing PHP. But exception is a traditional
        machinism in programming languages. I'm very doubt about this.
        In procedure language, we return error code when we meet an error. So
        we need to design error code table and judge them in several
        statements. Finally they become boring.
        But how about use exception in OOP? Did we drop all "return error
        code" styles?
        If i want to fetch a webpage:
        >
        <?php
        function fetchPage($url)
        {
        //...do something
        >
        //if the net speed is very slow, cause we can't fetch the page
        throw new SlowNetSpeed("p age can't be getted");
        >
        //if the page is moved
        throw new NoPage("page does't exist");
        >
        //...do something
        }
        >
        // so what can i do, if i want the fetchPage procedure go on fetching
        when SlowNetSpeed Exception happen?
        // it stop when NoPage Exception happen?
        while (1)
        {
        try
        {
        $c = fetchPage('Some _Where');
        // do something
        break;
        }
        catch (SlowNetSpeed $e)
        {
        }
        catch(NoPage $e)
        {
        break;
        }
        }
        ?>
        It is very ugly if there exists more Exceptions and other procedure.
        >
        Then i'm missing "return error code" style. But i know "return error
        code" is not a good method when we deal with error. And exception is
        also an ugly grammer when we want to keep code clean.
        >
        Exceptions originally were designed to handle unexpected conditions,
        i.e. connection to a database failed. They really weren't designed to
        replace normal error processing (i.e. userid/password mismatch).

        Normal errors are generally handled by the calling routine, but
        unexpected conditions may be handled by the immediate caller - or
        several layers higher. Exceptions give the ability to handle the
        condition as high in the calling hierarchy as you need to, without
        having to pass return codes from each routine in the which has been called.

        I still use them in this way, and it works well.

        --
        =============== ===
        Remove the "x" from my email address
        Jerry Stuckle
        JDS Computer Training Corp.
        jstucklex@attgl obal.net
        =============== ===

        Comment

        • Henk verhoeven

          #5
          Re: Exception : an ugly grammer in programming

          Jerry Stuckle wrote:
          Exceptions originally were designed to handle unexpected conditions,
          i.e. connection to a database failed. They really weren't designed to
          replace normal error processing (i.e. userid/password mismatch).
          >
          Normal errors are generally handled by the calling routine, but
          unexpected conditions may be handled by the immediate caller - or
          several layers higher. Exceptions give the ability to handle the
          condition as high in the calling hierarchy as you need to, without
          having to pass return codes from each routine in the which has been called.
          >
          I still use them in this way, and it works well.
          >
          I agree. And for errors that should just be debugged a custom error
          handler can output a nice walkback (if under development) or log it with
          usefull info (if in production).

          Greetings,

          Henk,
          www.phpPeanuts.org.

          Comment

          • Yarco

            #6
            Re: Exception : an ugly grammer in programming

            Erm...I'm thinking about the differences between error table and
            exception.
            It seems only one difference -- Exception can be caught in high level.

            Do you mean we need to use them togather?

            On Jul 17, 8:16 pm, Jerry Stuckle <jstuck...@attg lobal.netwrote:
            Yarco wrote:
            Well, friend. Yes, I'm doing PHP. But exception is a traditional
            machinism in programming languages. I'm very doubt about this.
            In procedure language, we return error code when we meet an error. So
            we need to design error code table and judge them in several
            statements. Finally they become boring.
            But how about use exception in OOP? Did we drop all "return error
            code" styles?
            If i want to fetch a webpage:
            >
            <?php
            function fetchPage($url)
            {
            //...do something
            >
            //if the net speed is very slow, cause we can't fetch the page
            throw new SlowNetSpeed("p age can't be getted");
            >
            //if the page is moved
            throw new NoPage("page does't exist");
            >
            //...do something
            }
            >
            // so what can i do, if i want the fetchPage procedure go on fetching
            when SlowNetSpeed Exception happen?
            // it stop when NoPage Exception happen?
            while (1)
            {
            try
            {
            $c = fetchPage('Some _Where');
            // do something
            break;
            }
            catch (SlowNetSpeed $e)
            {
            }
            catch(NoPage $e)
            {
            break;
            }
            }
            ?>
            It is very ugly if there exists more Exceptions and other procedure.
            >
            Then i'm missing "return error code" style. But i know "return error
            code" is not a good method when we deal with error. And exception is
            also an ugly grammer when we want to keep code clean.
            >
            Exceptions originally were designed to handle unexpected conditions,
            i.e. connection to a database failed. They really weren't designed to
            replace normal error processing (i.e. userid/password mismatch).
            >
            Normal errors are generally handled by the calling routine, but
            unexpected conditions may be handled by the immediate caller - or
            several layers higher. Exceptions give the ability to handle the
            condition as high in the calling hierarchy as you need to, without
            having to pass return codes from each routine in the which has been called.
            >
            I still use them in this way, and it works well.
            >
            --
            =============== ===
            Remove the "x" from my email address
            Jerry Stuckle
            JDS Computer Training Corp.
            jstuck...@attgl obal.net
            =============== ===

            Comment

            • Jerry Stuckle

              #7
              Re: Exception : an ugly grammer in programming

              Yarco wrote:
              On Jul 17, 8:16 pm, Jerry Stuckle <jstuck...@attg lobal.netwrote:
              >Yarco wrote:
              >>Well, friend. Yes, I'm doing PHP. But exception is a traditional
              >>machinism in programming languages. I'm very doubt about this.
              >>In procedure language, we return error code when we meet an error. So
              >>we need to design error code table and judge them in several
              >>statements. Finally they become boring.
              >>But how about use exception in OOP? Did we drop all "return error
              >>code" styles?
              >>If i want to fetch a webpage:
              >><?php
              >>function fetchPage($url)
              >>{
              >> //...do something
              >> //if the net speed is very slow, cause we can't fetch the page
              >> throw new SlowNetSpeed("p age can't be getted");
              >> //if the page is moved
              >> throw new NoPage("page does't exist");
              >> //...do something
              >>}
              >>// so what can i do, if i want the fetchPage procedure go on fetching
              >>when SlowNetSpeed Exception happen?
              >>// it stop when NoPage Exception happen?
              >>while (1)
              >>{
              >> try
              >> {
              >> $c = fetchPage('Some _Where');
              >> // do something
              >> break;
              >> }
              >> catch (SlowNetSpeed $e)
              >> {
              >> }
              >> catch(NoPage $e)
              >> {
              >> break;
              >> }
              >>}
              >>?>
              >>It is very ugly if there exists more Exceptions and other procedure.
              >>Then i'm missing "return error code" style. But i know "return error
              >>code" is not a good method when we deal with error. And exception is
              >>also an ugly grammer when we want to keep code clean.
              >Exceptions originally were designed to handle unexpected conditions,
              >i.e. connection to a database failed. They really weren't designed to
              >replace normal error processing (i.e. userid/password mismatch).
              >>
              >Normal errors are generally handled by the calling routine, but
              >unexpected conditions may be handled by the immediate caller - or
              >several layers higher. Exceptions give the ability to handle the
              >condition as high in the calling hierarchy as you need to, without
              >having to pass return codes from each routine in the which has been called.
              >>
              >I still use them in this way, and it works well.
              >>
              Erm...I'm thinking about the differences between error table and
              exception.
              It seems only one difference -- Exception can be caught in high level.
              >
              Do you mean we need to use them togather?
              >
              (Top posting fixed)

              I use both - which one depends on what I'm doing. If it's an error
              which I expect to occur, i.e. "not found" on a database search,
              incorrect (or missing) data in an entry field, etc., then I return an
              error code. However, if it's an unexpected condition, i.e. unable to
              connect to a database which should exist, then I return an exception.

              P.S. Please don't top post. Thanks.

              --
              =============== ===
              Remove the "x" from my email address
              Jerry Stuckle
              JDS Computer Training Corp.
              jstucklex@attgl obal.net
              =============== ===

              Comment

              • Joe Scylla

                #8
                Re: Exception : an ugly grammer in programming

                Yarco wrote:
                Well, friend. Yes, I'm doing PHP. But exception is a traditional
                machinism in programming languages. I'm very doubt about this.
                In procedure language, we return error code when we meet an error. So
                we need to design error code table and judge them in several
                statements. Finally they become boring.
                But how about use exception in OOP? Did we drop all "return error
                code" styles?
                If i want to fetch a webpage:
                .... snipped...
                It is very ugly if there exists more Exceptions and other procedure.
                >
                Then i'm missing "return error code" style. But i know "return error
                code" is not a good method when we deal with error. And exception is
                also an ugly grammer when we want to keep code clean.
                Exceptions don't replace conventional error management. On the most
                cases i only use exceptions on function/method scope and return FALSE is
                a Exception got thrown. In the most cases it's not relevant why the
                operation failed for the caller.

                <code>
                function parse_file($fil e)
                {
                try
                {
                if (!@file_exists( $file))
                throw new Exception("File does not exist");
                if (!$content = @file_get_conte nts($file))
                throw new Exception("Erro r reading file!");
                //do something with content
                return $content;
                }
                catch (Exception $e)
                {
                //do something with your Exception
                return false; //or a error code or a default value
                }
                }
                </code>

                I'm using a own Exception class fetching the system error message
                (error_get_last , mysql_error, ...) and writing a log file and have a
                LastError/LastErrors property for fetching the last error message.

                Comment

                Working...