What happens exactly internally when I terminate my Python script using Ctrl+c?
Question: These days I am learning Python's Exception handling features deeply. I
encountered `exception SystemExit`. While reading about this from [official
Python Docs](http://docs.python.org/2/library/exceptions.html) I got question
in mind that what exactly would have happen when I terminate Python script by
pressing `Ctrl`+`c`?

lets take this sample code:

    
    
    def func1(a,b):
        print "func1: "+str(a/b)
        #some more functions
    
    def func2(a,b):
        print "func2: "+str(a/b)
        #some more functions
    
    if __name__=="__main__":
        import random
    
        count=0
        for i in range(1000000):
                count=count+1
                print "count: "+str(count)
                try:
                        func1(random.randint(-2,3),random.randint(-2,3))
                except KeyboardInterrupt:
                        raise
                except:
                        print "error in func1"
                try:
                        func2(random.randint(-2,3),random.randint(-2,3))
                except KeyboardInterrupt:
                        raise
                except:
                        print "error in func2"
    
                print "\n"
    

In this sample code I am catching `KeyboardInterrupt` so I can stop my script
by pressing `Ctrl`+`c`. Should I catch `SystemExit` too to make this code more
mature? if yes then why? actually this question is source of my main question
which appear on title. so don't consider that I am asking two different
question in one post.


Answer: You usually not need to catch `SystemExit` as it is what makes
[`exit()`](http://docs.python.org/2/library/constants.html#exit) and
[`sys.exit()`](http://docs.python.org/2/library/sys.html#sys.exit) functions
work:

> **sys.exit([arg])**
>
> Exit from Python. This is implemented by raising the `SystemExit` exception,
> so cleanup actions specified by `finally` clauses of `try` statements are
> honored, and it is possible to intercept the exit attempt at an outer level.

Example:

    
    
    try:
        exit()
    except SystemExit:
        print "caught"
    

Therefore, you usually don't want to catch all exceptions in the first place
(by using an empty `except:` clause). The best approach is generally to make
your exception handlers as specific as possible. It otherwise makes debugging
your application exceptionally hard, as it either hides errors entirely or at
least makes it hard to diagnose the details.

