
Introduction to Python KeyboardInterrupt
We already know the exceptions and how to handle them in Python. In layman’s languageexceptions are something that interrupts the normal flow of the program. Similarlythe KeyboardInterrupt exception is a Python exception that is raised when the user or programmer interrupts the normal execution of a program. The interpreter in Python regularly checks for any interrupts while executing the program. In Pythonthe interpreter throws a KeyboardInterrupt exception when the user/programmer presses the ctrl – c or del key either accidentally or intentionally.
Syntax:
As observed in the example abovethe KeyboardInterrupt exception is a standard exception used to handle keyboard-related issues. There is no specific syntax unique to the KeyboardInterrupt exception in Python; it is handled like any other exception using the try-except block within the code. The code that might generate the exception is placed within the try blockand it is either explicitly raised using the ‘raise’ keyword or automatically raised by the Python interpreter. To handle the exception and perform desired actionsspecific code is written within the except block.
try:
# code that can raise the exception
# raising this exception is not mandatory
raise KeyboardInterrupt
except KeyboardInterrupt:
# code to perform any specific tasks to catch that exception
How does KeyboardInterrupt Exception work in Python?
One of the most frustrating aspects of working with Python is that it terminates the program when the user presses Ctrl-Cwhether intentionally or accidentally. This can be a significant issueespecially when dealing with tasks such as processing bulk dataretrieving records from a databaseor executing large programs that handle multiple tasks simultaneously. This exception works very simplylike other exceptions in Python. The only thing about this exception is that it is user generatedand the computer is not involved in raising it. In order to understand the working of KeyboardInterrupt exception in Pythonlet’s understand the below-written code first.
Code:
try:
# code inside the try block which can cause an exception
# taking the input ‘name’ from the user
name = input('Enter the name of the user ')
# writing the different exception class to catch/ handle the exception
except EOFError:
print('Hello user it is EOF exceptionplease enter something and run me again')
except KeyboardInterrupt:
print('Hello user you have pressed ctrl-c button.')
# If both the above exception class does not matchelse part will get executed
else:
print('Hello user there is some format error')
In the above code:
- Firstthe code inside the try block is executed.
- If the user presses the ctrl – can exception will be raisedand execution of the rest of the statements of the try block is stopped and will move the except block of the raised exception.
- If no exceptions occur within the try blockthe execution continues normallyand no statements within the ‘except’ block are executed.
- If an exception is raised but does not match the class name specified in the exception handler following the ‘except’ keywordthe program will search for a corresponding catch block outside the inner try block to handle it. If a suitable catch block is not foundthe program will exit with a standard Python message.
How to Avoid KeyboardInterrupt Exceptions in Python?
- There is no such way to avoid the KeyboardInterrupt exception in Pythonas it will automatically raise the KeyboardInterrupt exception when the user presses the ctrl – c. There are a few things that we can do in order to avoid this.
- As we all knowthat final block is always executed. So if the exception is raised and we are tangled in some infinite loopthen we can write a clean code in the final block (which will get executed in every case)which can help us to backtrack the situation.
- It depends on how the programmer he/she codes to avoid this situationas every programmer has a different way of thinking and hence coding.
Example of Python KeyboardInterrupt
Given below is the example mentioned. General output when the user presses the ctrl – c button.
Code:
try:
# code inside the try block which can cause an exception
# taking the input ‘name’ from the user
name = input('Enter the name of the user ')
# writing the different exception class to catch/ handle the exception
except EOFError:
print('Hello user it is EOF exceptionplease enter something and run me again')
except KeyboardInterrupt:
print('Hello user you have pressed ctrl-c button.')
# If both the above exception class does not matchelse part will get executed
else:
print('Hello user there is some format error')
Output 1:
When the user presses the ctrl -c button on asking the username by the programthe below output is generated.
Explanation:
In the above outputthe print statement written for the KeyboardInterrupt exception is displayed as the user presses the ctrl – cwhich is a user interrupt exception.
Output 2:
When the user presses the ctrl – d button on asking for the username by the programthe below-given output is generated.
Explanation:
In the provided outputwhen the user presses the Ctrl-D buttonindicating the end of the filea print statement under the EOF exception class is displayed. This signifies that the specified exception class is checked when the exception occurs.
Conclusion
The above article provides a clear explanation of the KeyboardInterrupt exception in Python. For any programmerbe it a newbie or an expertit is very important to understand every type of exception in detail to deal with them accordingly and write a program efficiently (able to handle any kind of such situation).
Recommended Articles
This is a guide to Python KeyboardInterrupt. Here we discuss how KeyboardInterrupt exception works and how to avoid KeyboardInterrupt exceptions in Python with respective examples. You may also have a look at the following articles to learn more –
< type="text/css">@media only screen and (max-width: 896px) and (min-width: 320px) { .content-sidebar-wrap.content-sidebar-wrap.c2 { padding: 2vw 5vw!important; display: block; } .five-sixths.box-div { width: 100% !important; margin-left: 0 !important; min-height: unset !important; } .breadcrumb.breadcrumb.rbc3 { padding-top: 90px!important; padding-left: 15px !important; margin-bottom: 20px!important; } .pn-ProductNav_Wrapper,.pn-ProductNav_Wrapper.rrb7 {top: 69px!important;} .pn-Advancer_Right {margin:0} } .content-sidebar-wrap { padding: 22vw 5vw; } .site-inner.rounded-list aul.rounded-list li.sub#sticky-title.rel-courses#sticky { background-color: #fff !important; } aside.sidebar.sidebar-primary.widget-area { flex: 1; margin-left: 40px; padding: 0 0 0 50px; flex: 1; } .single-title {width:100%} .has-fixed-header .site-header{ background: #fff; box-shadow: 0 0 2rem rgb(35 44 57 / 20%); } .menu-toggle span.menu-toggle span::before.menu-toggle span::after{ background: #000; } @media (max-device-width: 520px) and (min-device-width: 320px){ .nav-primary.site-inner.rel-courses { background-color:#fff !important; } } @media (min-width: 896px){ .content-sidebar-wrap.c1.c3.content-sidebar-wrap.c3.c2.content-sidebar-wrap.c2.c1.content-sidebar-wrap.c3 { padding: 2rem 0!important; } .content { width: -webkit-calc(55.5% - 1rem) !important; width: calc(55.5% - 1rem) !important; } .site-inner .content-sidebar-wrap { padding: 2rem 0!important; } .site-header > .wrap { padding: 0rem 0; } } .breadcrumb { /*margin-bottom: 20px!important;*/ padding-top: 140px; padding-left: 120px; } .breadcrumb.rbc3 { padding-top: 135px!important; } @media (min-width: 768px){ .wrap { width: 98%; max-width: 100%; padding: 0; } footer.site-footer .wrap { width: 90%; max-width: 1280px; } .content { padding: 2rem!important; border-radius:10px; } .content-sidebar-wrap .content { padding: 0rem !important; } } .has-fixed-header .site-header.fixed .mega-search.mega-search-open input[type=text] { border: 1px solid #ccc!important; } .has-fixed-header .site-header.fixed li.mega-menu-item-137987 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-138113 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-370765 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-138221 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-138228 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-138242 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-138292 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-138378 a.mega-menu-link.has-fixed-header .site-header.fixed li.mega-menu-item-138454 a.mega-menu-link.button.accent { background-image: linear-gradient(to top,#e93f33,#ea4b32,#eb5632,#ec6032,#ec6a33)!important; } h1h2h3h4h5h6.entry-content h2{ font-family: 'Montserrat'sans-serif!important; color: #10656d!important; } .entry-content li.entry-content ol.entry-content p.entry-content table.entry-content ul { color:#273239!important; font-family: -apple-system,system-ui,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen-Sans,Ubuntu,Cantarell,'Helvetica Neue',Arial,sans-serif;!important; font-size:19px !important; line-height:1.9 !important; } .entry-content h2 { border-bottom: 2px solid #10656d !important; } .breadcrumb a { color: #273239 !important; font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",Arial,sans-serif !important; text-decoration: underline; font-weight: 500; font-size:1.4rem !important; } bodypul.rounded-list { font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",Arial,sans-serif!important; } .sname#ifclassul.rounded-list li.sub .subli li:hover a { color: #0693a0 !important; } ul.rounded-list li.sub .subli li a { color: #273239 !important; font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",Arial,sans-serif!important; } #fix-bar::-webkit-scrollbar-thumb{ background: #B6B6B6 !important; -webkit-box-shadow: inset 0 0 6px rgb(0 0 0 / 30%); background-color: #F5F5F5; border-radius: 10px 10px 0px 0px!important; } ul.rounded-list li.sub.subcat-name { font-family: 'Montserrat'sans-serif!important; } .single-title a { font-size: 1.4rem !important; font-weight: 500; text-decoration: none !important; color: #273239 !important; } .single-title span { font-size: 14px !important; } .entry-content a { color: #0693a0 !important; font-weight: 700; text-decoration: none !important; } h3:after { background: #0693a0 !important; } #fix-bar::-webkit-scrollbar { width: 10px !important; height: 5px; } ul.rounded-list li.sub .subli li a {font-weight: 500 !important;} #ifclass{display:none!important} .rounded-list ul.subli li a:before {content:none!important} .rounded-list a{padding:.1em .4em .1em 2em!important} ul.rounded-list ul li {line-height: 2.4!important;} /*.entry-content h4.entry-content h5 { color: #0693a0 !important; }*/ .entry-content h5 {font-size:20px} .entry-content pre {background-color: #fff !important;padding: 0 !important;border-left: none !important;border: none !important;} .subcat-name {color:#0693a0!important;font-weight:700;} .contentinner h4 {font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",Arial,sans-serif!important} table td,th{border-left:2px solid #d2d2d2;vertical-align:text-top}#list2::-webkit-scrollbar,#sticky::-webkit-scrollbar,#ullist::-webkit-scrollbar{width:5px}#list2::-webkit-scrollbar-track,#ullist::-webkit-scrollbar-track{background:#f1f1f1}#list2::-webkit-scrollbar-thumb,#ullist::-webkit-scrollbar-thumb{background:#f1f1f1}#list2::-webkit-scrollbar-thumb:hover,#ullist::-webkit-scrollbar-thumb:hover{background:#888}#list2:hover::-webkit-scrollbar-thumb,#ullist:hover::-webkit-scrollbar-thumb{background:#888}@media (max-device-width:480px) and (min-device-width:320px){.entry-content code{width:auto;overflow:scroll}.entry-content pre{width:auto;overflow:scroll}.entry-content .wp-video{width:auto!important}}@media (max-device-width:767px) and (min-device-width:481px){.entry-content code{width:470px;overflow:scroll}}@media (max-device-width:890px) and (min-device-width:768px){.entry-content code{width:750px;overflow:scroll}}@media only screen and (min-device-width:891px){.entry-content code{width:auto}}.breadcrumb a{color:#e93f33;text-decoration:underline;font-family:'Nunito Sans',-apple-system,blinkmacsystemfont,'Segoe UI',roboto,helvetica,arial,sans-serif}.entry-content a{color:#e93f33;border-bottom:1px solid;text-decoration:none}.entry-content a:focus,.entry-content a:hover{border-bottom:transparent}@media (min-width:768px){h1{font-size:3em}h2{font-size:2em}h3{font-size:1.8em}h4{font-size:1.5em}h5{font-size:1.4em}h6{font-size:1.3em}.content-sidebar-wrap{width: 98%; max-width: 1200px; display: flex; flex-wrap: wrap;}}h2{font-size:2em}h3{font-size:1.8em}h4{font-size:1.5em}h5{font-size:1.4em}h6{font-size:1.3em}body>div{font-size:18px;font-size:1.6rem}b,h1,h2,h3,h4,h5,h6,strong{font-family:'Nunito Sans',-apple-system,blinkmacsystemfont,'Segoe UI',roboto,helvetica,arial,sans-serif;font-weight:700!important}@media (min-width:768px){body>div{font-size:1.8rem}.content { padding: 0 2rem!important; }}.entry-content ol,.entry-content ul{margin-bottom:1.618em;margin-left:4rem}.entry-content li,.entry-content ol,.entry-content p,.entry-content table,.entry-content ul{color:#4d5968;line-height:2;font-family:'Nunito Sans',-apple-system,blinkmacsystemfont,'Segoe UI',roboto,helvetica,arial,sans-serif}@media (min-width:896px){.content-sidebar-wrap{padding:3rem 0!important}.content{ width: -webkit-calc(57.5% - 1rem); width: calc(57.5% - 1rem); }.sidebar-primary { width: 23%; }}.leftshift{left:70%!important}.content-sidebar-wrap-bg{background: #0a635fab;}.inline-pp-banner-bg {background: #faffbd82;}.img-op{opacity: 0.5;}@media only screen and (min-width: 1024px) { .sidebar-content-sidebar .sidebar-secondary { order: 0; width: 19.5%; } .sidebar-content-sidebar .content { order: 1; } .sidebar-content-sidebar .sidebar-primary { order: 2; } } .breadcrumb{margin-bottom:0} .fa-chevron-right:before{ color: #000000; content: url(https://cdn.educba.com/academy/wp-content/uploads/2022/12/b_arrow.svg); width: 12px; height: 18px; padding-right: 0.9rem; font-size: 0rem; font-weight: 700; vertical-align: middle;} .swp_social_panel a {color:white!important}.othr-cour a{color:#4a4a4a!important;border-bottom:none}.othr-cour a:hover{border-bottom:1px solid!important}.box-div .fa-book:before{content:"\f14e"}.box-div .fa-book{background-image:linear-gradient(to top,#0ba360 0,#3cba92 100%);padding:15px;border-radius:5px;color:#f0f8ff;font-size:50px}.box-div .fa-flash:before,.fa-bolt:before{content:"\f1fa"}.box-div .box-btn{width:max-content;cursor:pointer;transition:.2s;padding:10px 30px;line-height:1.33;border-radius:4px;color:#fff;background:#ff8c00;border:thin solid #ff8c00;margin-bottom:0;font-weight:700;text-align:center;vertical-align:middle;font-size:15px;display:block;letter-spacing:1px;background-image:linear-gradient(to top,#e93f33,#ea4b32,#eb5632,#ec6032,#ec6a33)}.box-div{margin:10px 0 25px;padding:24px;width:100%}.box-div .course-title{font-weight:700;font-size:1.3em;letter-spacing:1px;display:block;min-height:110px}.box-div .fa-star{font-size:15px;color:#f5af12;margin-right:4px}.box-div .price-box{text-align:-webkit-center}@media (min-device-width :320px) and (max-device-width :520px){.box-div .banr-image{display:none}.box-div .price-box{text-align:-webkit-left;margin:15px 0}}@media (min-device-width :320px) and (max-device-width :767px){.sale-bf{position:absolute;width:80px;margin-top:-5.4em;right:0}}.box-div .othr-cour{border-radius:4px;border:1px solid #4a4a4a;margin-right:12px;padding:5px 10px;font-size:14px;font-weight:400;display:inline-block;margin-bottom:5px;cursor:pointer;line-height:1.4}.box-div .rel-cour{font-size:16px;padding-bottom:5px}@media (min-device-width :768px){.centertext{text-align:center}.sale-bf{position:absolute;width:120px;margin-top:-6.1em;right:2.5em}}.blg-price{font-size:1.5em;font-weight:700;}.blg-str-price strike{font-size:1.2em;color:grey;font-weight:700;}.box-div hr{margin:0 0 .5em;padding:.5em 0 0}.box-div .course-title{line-height:25px}.box-div .banr-image{text-align:center;margin-top:20px}.box-div .bundle_link{text-decoration:none;color:#000!important;border:0}.box-div .bullets{font-weight:400;font-size:.9em}#banner_1_rb .three-sixths{margin-top:15px}#banner_1_rb .five-sixths{width:100%;margin:0}#banner_1_rb .course-price{font-size:1em}#banner_1_rb:hover{-webkit-box-shadow:0 9px 5px -6px rgba(0,0,0,.75);-moz-box-shadow:0 9px 5px -6px rgba(0,0,0,.75);box-shadow:0 9px 5px -6px rgba(0,0,0,.75)}#banner_1_rb{background-image:url('https://cdn.educba.com/academy/wp-content/uploads/2022/11/Project-Management.jpg');padding:30px 14px;background-size:cover;background-position:top center;position:relative;width:100%;font-family:Montserrat,sans-serif!important}.bf_badge{position:absolute;right:-2px;top:-12px;width:90px;}@media only screen and (max-width:896px) and (min-width:320px){.three-sixths{width:100%!important}#banner_1_rb{width:100%!important}.uk-grid-margin{padding-left:0!important}.bf_badge{position:absolute;right:-1px;top:-9px!important;width:70px!important;}} >
