Difference between PHP and Python finally and exit

Summary

The difference is whether or not to handle ʻexit` as an exception.

PHP

You can find it in the explanation and user notes of ʻexit`.

PHP: exit - Manual

Example 3 An example of a shutdown function or destructor being executed

>
<?php
class Foo
{
    public function __destruct()
    {
        echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
    }
}
>
function shutdown()
{
    echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}
>
$foo = new Foo();
register_shutdown_function('shutdown');
>
exit();
echo 'This is not output.';
?>

The output of the above example is as follows.

 Shutdown: shutdown()
 Destruct: Foo::__destruct()

PHP: exit - Manual : User Contributed Notes

A side-note for the use of exit with finally: if you exit somewhere in a try block, the finally won't be executed. Could not sound obvious: for instance in Java you never issue an exit, at least a return in your controller; in PHP instead you could find yourself exiting from a controller method (e.g. in case you issue a redirect).

Here follows the POC:

<?php
echo "testing finally wit exit\n";
>
try {
    echo "In try, exiting\n";
>
    exit;
} catch(Exception $e) {
    echo "catched\n";
} finally {
    echo "in finally\n";
}
>
echo "In the end\n";
?>

This will print:

testing finally wit exit In try, exiting

There is also a way to throw an exception instead of exit and write the termination process with catch, but it seems that it is not a perfect alternative.

Naturally, I tried running it on PHP7, but the result was the same.

Python

Uchan Note: Differences between Python exit (), sys.exit (), os._exit () It is a glance if you look at it.

Since exceptions are thrown except for ʻos._exit (), finally is also relevant. When it is said that ʻos._exit () is equivalent to PHP's ʻexit ()`, it looks a little different.

exit

4. Built-in constants — Python 2.7.x documentation

An object that prints a message like “Use quit () or Ctrl-D (ie EOF) to exit” when displayed and sends a SystemExit with the specified exit code when called. ..

sys.exit()

28.1. sys — System Parameters and Functions — Python 2.7.x Documentation

Exit Python. Since ʻexit ()sends aSystemExit, it is possible to describe the termination process in the finallyclause of thetry statement, or to catch an exception at a higher level and interrupt the ʻexit process. I can do it. (Omitted) Ultimately, ʻexit ()` is “only” throwing an exception, so when it is called from the main thread, it just terminates the process and does not block the exception.

6. Built-in exceptions — Python 2.7.x documentation

This exception is thrown by the sys.exit () function. If this exception is not handled, the Python interpreter will exit without displaying any tracebacks on the stack. If the associated value is a regular integer, it represents the system exit status (passed to the exit () function). If the value is None, the exit status is 0. For other types (such as strings), the value of that object is displayed and the exit status is 1.

The instance of this exception has the attribute code. This value is set to the exit status or error message (None by default). Also, this exception is not strictly an error, so it derives from BaseException instead of StandardError.

sys.exit () ensures that the cleanup process (finally clause of the try statement) is executed and that the script can be executed without risking the debugger getting out of control. Translated into exceptions. You can use the os._exit () function when you really need to exit immediately (for example, in a child process after calling fork ()).

This exception inherits from BaseException rather than from StandardError or Exception so that the code that catches the Exception doesn't accidentally catch it. This will steadily propagate this exception to the caller and terminate the interpreter.

Changed in version 2.5: Changed to inherit BaseException.

Exactly! is not it.

os._exit()

15.1. Os — Miscellaneous operating system interfaces — Python 2.7.x documentation

Exit the process with exit status n. At this time, the cleanup handler is not called and the standard I / O buffer is not flushed.

Related articles

From the same blog.

It's a transition from the era without finally to the era after implementation, Combined with the operation of ʻexit` this time, I feel that the destructor has been re-recognized.

Recommended Posts

Difference between PHP and Python finally and exit
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
difference between statements (statements) and expressions (expressions) in Python
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
[Python] Difference between class method and static method
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
Summary of the differences between PHP and Python
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Difference between Ruby and Python in terms of variables
Difference between regression and classification
Difference between return, return None, and no return description in Python
Difference between np.array and np.arange
Difference between MicroPython and CPython
Difference between ps a and ps -a
Difference between return and print-Python
Python module num2words Difference in behavior between English and Russian
Python> Difference between inpbt and print (inpbt) output> [1. 2. 3.] / array ([1., 2., 3.], dtype = float32)
List concatenation method in python, difference between list.extend () and “+” operator
Difference between SQLAlchemy filter () and filter_by ()
Memorandum (difference between csv.reader and csv.dictreader)
(Note) Difference between gateway and default gateway
Cooperation between python module and API
Difference between Numpy randint and Random randint
Differences between Python, stftime and strptime
Difference between sort and sorted (memorial)
Difference between SQLAlchemy flush () and commit ()
Difference in how to write if statement between ruby ​​and python
Transcendental simple and clear! !! Difference between single quotes and double quotes in Python
Python / Numpy> Link> Difference between numpy.random and random.random> thread-safe or not
Summary of differences between Python and PHP (comparison table of main items)
File open function in Python3 (difference between open and codecs.open and speed comparison)
Communicate between Elixir and Python with gRPC
Differences in authenticity between Python and JavaScript
Avoid nested loops in PHP and Python
Differences between Ruby and Python in scope
[Xg boost] Difference between softmax and softprob
[Django ORM] Difference between values () and only ()
Difference between linear regression, Ridge regression and Lasso regression
[Basic grammar] Differences between Ruby / Python / PHP
Difference between docker-compose env_file and .env file
[Python3] Switch between Shift_JIS, UTF-8 and ASCII
speed difference between wsgi, Bottle and Flask
Differences in multithreading between Python and Jython
Differences between Ruby and Python (basic syntax)
Difference between numpy.ndarray and list (dimension, size)
Correspondence between Python built-in functions and Rust
Difference between ls -l and cat command
Exchange encrypted data between Python and C #