M
M
mafia82016-09-13 00:31:34
PHP
mafia8, 2016-09-13 00:31:34

How to catch an exception in php?

<?
$a='a';
try {
  $a[1250000000]='b';
  // Это поймать надо 
  // PHP Fatal error:  Out of memory (allocated 524288) 
  // (tried to allocate 1250000002 bytes)
  $b=1/0; // и это
} catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Or set up php (console mode) to allocate memory.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2016-09-13
@mafia8

$a[1250000000]='b'is a correct expression. what is there to catch?
$b=1/0;- warning, which is caught through the standard set_error_handler .
i.e. something like this:

<?php
function error_handler( $errno, $errmsg, $filename, $linenum, $vars ) {
    // error was suppressed with the @-operator
    if ( 0 === error_reporting() )
      return false;

    if ( $errno !== E_ERROR )
      throw new \ErrorException( sprintf('%s: %s', $errno, $errmsg ), 0, $errno, $filename, $linenum );

}
set_error_handler( 'error_handler' );

try {
  $a[1250000000]='b'; // Это поймать надо
  $b=1/0; // и это
} catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n";
}
ideone.com/54gPMt

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question