PHP.mk документација

OutOfBoundsException

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

class.outofboundsexception.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека class.outofboundsexception.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
OutOfBoundsException

Референца за `class.outofboundsexception.php` со подобрена типографија и навигација.

class.outofboundsexception.php

Класата OutOfBoundsException

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Вовед

Исклучок што се фрла ако вредноста не е валиден клуч. Ова претставува грешки што не можат да се откријат во време на компајлирање.

Синопсис на класата

class OutOfBoundsException extends RuntimeException {
/* Наследени својства */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
/* Наследени методи */
public Exception::__construct(string $message = "", int $code = 0, ?Проверува тврдење $previous = null)
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
}

Белешки од корисници 5 белешки

Јакуб Адамчик
пред 8 години
I see this in this way:
By definiton, OutOfRangeException should be use to when potential problem is logical. This (OutOfBoundsException) is for runtime, so it's perfect for catching errors which occur because of bad result from database and simillar.

Example of using OutOfBoundSException (see also note in "OutOfRangeException class" article):

<?php
class HandleApplication {
    public function __construct($_POST) {
        if(!isset($_POST['secretCode'])
            throw new OutOfBoundsException('Application hasn't sent secret code for authenticate');
}
sricharan dot krishnan at gmail dot com
пред 9 години
An example where an OutOfBoundsException can occur:
Lets say post a certain division process, we wish to access a value in an Array [provided ofcourse if the result value of the division is within the size of the Array]..

try{
    if ($iNum2 == 0){
        throw new Exception("Division by Zero");
    }
    $iResult = $iNum1 / $iNum2;
    echo ("Division result is: ".($iResult)."<br/>");
}
catch (Exception $e){
    echo ("Division by Zero is not possible.".($e)."<br/>");
}

$rg_Array = array(1,2,3,4);

try{
    if ($iResult > sizeof($rg_Array)- 1){
        throw new Exception("Exceeding key values");
    }
echo ("Capturing value from \$rg_Array post Division process:".($rg_Array[$iResult])."<br/>");
}
catch (Exception $e){
    echo ("Value of Division result is out of bounds for the array.".($e)."<br/>");
}
?>
Јакоб В. Расмусен
пред 10 години
OutOfRangeException is for Integers out of range.
OutOfBoundsException is for key values, not found in the target array.

Editor's note: This is incorrect; OutOfRangeException has *nothing* to do with Integer ranges. I decided to keep this highly voted comment even though it is wrong for education's sake.
Анонимен
3 години пред
I would probably repeat @jacub's answer, but I see the distinction as following:

`OutOfBoundsException` you throw, when _you_ _set_ bounds and do not wish them to be crossed by an external entity, but they may be.
Example: you ask for a number in range [1, 6] and user input 0 or 7 or what else. You throw an exception indicating user error they could amend.

`OutOfRangeException` you throw, when you expect value within allowed boundary, but actual operation fails.
Example: You are trying to access external API call using information provided by the API itself, and it suddenly tell you that the reference key is not pointing to a valid object. You throw an exception indicating internal failure that the user is unable to correct.

In both cases, the key word is "you throw". Both exceptions are generated at runtime, but the latter describes a situation that should not happen, ever, if a system is configured correctly.
евгениа дот шањон ат џимејл дот ком
пред 9 години
class MyDynamicTastyPie implements ArrayAccess{
    private $_pointeur = 0;
    private $_array = ['strawberry slice','white chocolate','nuts'];
    
    public function offsetExists($key){
        return isset($this->_array[$key]);
    }
    
    public function offsetGet($key){
        if ($key > count($this->_array)){
            throw new OutOfBoundsException('Your tasty pie doesn\'t contain so slices');
        }
        return $this->_array[$key];
    }
    
    public function offsetSet($key, $value){
        $this->_array[$key] =$value;
    }
    
    public function offsetUnset($key){
        unset($this->_array[$key]);
    }
    
    public function addSlice($slice){
        $this->_array[] = $slice;
    }
}

try {
    $myDynamicTastyPie = new MyDynamicTastyPie();
    $myDynamicTastyPie->addSlice('Black chocolate cream decoration');
    echo $myDynamicTastyPie[7];
}
catch(OutOfBoundsException $e){
    echo 'Here is your OutOfBoundsException!';
}
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.