Python Try Except - GeeksforGeeks (2024)

Last Updated : 13 Apr, 2023

Improve

Improve

Like Article

Like

Save

Report

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Note: For more information, refer to Errors and Exceptions in Python
Some of the common Exception Errors are :

  • IOError: if the file can’t be opened
  • KeyboardInterrupt: when an unrequired key is pressed by the user
  • ValueError: when the built-in function receives a wrong argument
  • EOFError: if End-Of-File is hit without reading any data
  • ImportError: if it is unable to find the module

Try Except in Python

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.

Syntax:

try: # Some Codeexcept: # Executed if error in the # try block

How try() works?

  • First, the try clause is executed i.e. the code between try.
  • If there is no exception, then only the try clause will run, except clause is finished.
  • If any exception occurs, the try clause will be skipped and except clause will run.
  • If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
  • A try statement can have more than one except clause

Code 1: No exception, so the try clause will run.

Python3

# Python code to illustrate

# working of try()

def divide(x, y):

try:

# Floor Division : Gives only Fractional Part as Answer

result = x // y

print("Yeah ! Your answer is :", result)

except ZeroDivisionError:

print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program

divide(3, 2)

Auxiliary Space: O(1)

Output :

Yeah ! Your answer is : 1

Code 1: There is an exception so only except clause will run.

Python3

# Python code to illustrate

# working of try()

def divide(x, y):

try:

# Floor Division : Gives only Fractional Part as Answer

result = x // y

print("Yeah ! Your answer is :", result)

except ZeroDivisionError:

print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program

divide(3, 0)

Output :

Sorry ! You are dividing by zero

Code 2: The other way of writing except statement, is shown below and in this way, it only accepts exceptions that you’re meant to catch or you can check which error is occurring.

Python3

# code

def divide(x, y):

try:

# Floor Division : Gives only Fractional Part as Answer

result = x // y

print("Yeah ! Your answer is :", result)

except Exception as e:

# By this way we can know about the type of error occurring

print("The error is: ",e)

divide(3, "GFG")

divide(3,0)

Output:

The error is: unsupported operand type(s) for //: 'int' and 'str'The error is: integer division or modulo by zero

Else Clause

In Python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.

Syntax:

try: # Some Codeexcept: # Executed if error in the # try blockelse: # execute if no exception

Code:

Python3

# Program to depict else clause with try-except

# Function which returns a/b

def AbyB(a , b):

try:

c = ((a+b) // (a-b))

except ZeroDivisionError:

print ("a/b result in 0")

else:

print (c)

# Driver program to test above function

AbyB(2.0, 3.0)

AbyB(3.0, 3.0)

Output:

-5.0a/b result in 0

Finally Keyword in Python

Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after the normal termination of the try block or after the try block terminates due to some exceptions.

Syntax:

try: # Some Codeexcept: # Executed if error in the # try blockelse: # execute if no exceptionfinally: # Some code .....(always executed)

Code:

Python3

# Python program to demonstrate finally

# No exception Exception raised in try block

try:

k = 5//0 # raises divide by zero exception.

print(k)

# handles zerodivision exception

except ZeroDivisionError:

print("Can't divide by zero")

finally:

# this block is always executed

# regardless of exception generation.

print('This is always executed')

Output:

Can't divide by zeroThis is always executed

Related Articles:

  • Output Questions
  • Exception Handling in Python
  • User-Defined Exceptions


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Python Try Except - GeeksforGeeks (2024)

References

Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 6272

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.