Skip to content

ThrowRawException ​

info on by default quick-fix

Group: Control flow · PhpStorm name: ThrowRawExceptionInspection

Throwing the base \Exception class gives callers nothing specific to catch; a more specific (SPL) exception class communicates intent better. Separately, throwing a standard-shaped exception without any constructor argument loses the diagnostic message.

Example ​

php
<?php
class QuietFailure extends \LogicException {
    function __construct()
    {
        parent::__construct("quiet", 7);
    }
}
class PresetFailure extends \DomainException {
    protected $message = 'preset text';
}
class PlainFailure extends \UnderflowException {}

function guard($n) {
    if ($n < 0) {
        throw new \Exception("negative $n");
    }
    if ($n === 0) {
        throw new Exception();
    }
    if ($n === 1) {
        throw new OutOfRangeException;
    }
    if ($n === 2) {
        throw new PlainFailure();
    }
    if ($n === 3) {
        throw new QuietFailure();
    }
    if ($n === 4) {
        throw new PresetFailure();
    }
    throw new LengthException('too long');
}
php
<?php
class QuietFailure extends \LogicException {
    function __construct()
    {
        parent::__construct("quiet", 7);
    }
}
class PresetFailure extends \DomainException {
    protected $message = 'preset text';
}
class PlainFailure extends \UnderflowException {}

function guard($n) {
    if ($n < 0) {
        throw new \RuntimeException("negative $n");
    }
    if ($n === 0) {
        throw new \RuntimeException();
    }
    if ($n === 1) {
        throw new OutOfRangeException;
    }
    if ($n === 2) {
        throw new PlainFailure();
    }
    if ($n === 3) {
        throw new QuietFailure();
    }
    if ($n === 4) {
        throw new PresetFailure();
    }
    throw new LengthException('too long');
}

Reported:

  • line 15: Throw a more specific exception class than \Exception.
  • line 18: Throw a more specific exception class than \Exception.
  • line 21: Pass a message when throwing this exception.
  • line 24: Pass a message when throwing this exception.

Options ​

OptionTypeDefaultEffect
REPORT_MISSING_ARGUMENTSbooltrueEnables D3 (exceptions created without any argument).

Configure ​

In custos.json:

json
{
  "rules": {
    "ThrowRawException": {
      "enabled": false,
      "options": {
        "REPORT_MISSING_ARGUMENTS": true
      }
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore ThrowRawException

/**
 * @noinspection ThrowRawExceptionInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.