0% found this document useful (0 votes)
11 views

CIC Hands On Python - s4

Uploaded by

Ns Arial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

CIC Hands On Python - s4

Uploaded by

Ns Arial
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

07

Try & Except

Prepared by : Abdelaziz Shaheen


LAB 6

1. Write a simple calculator


• Addition
• Subtraction
• Multiplication
• Division
Try to handle all the error that
may occur during the runtime.

Prepared by : Abdelaziz Shaheen


Try & Except
In Python, try and except are control flow statements used for
exception handling. Exception handling is a mechanism that
allows you to gracefully handle runtime errors and exceptions
that may occur during the execution of a program. By using try
and except blocks, you can prevent your program from crashing
when an error occurs and handle the error in a controlled manner.

Here's a brief explanation of how try and except work:

Try Block:
The try block contains the code that might raise an exception. You
place the code that you think might raise an exception inside the
try block. If an exception occurs within the try block, Python
immediately jumps out of that block and into the except block.

Except Block:
The except block contains the code that is executed if a specific
exception mentioned in the except statement occurs in the
corresponding try block. You can catch specific exceptions or catch
more general exceptions.

Prepared by : Abdelaziz Shaheen


Try & Except

except SomeException: Catches a specific exception named SomeException.


except AnotherException: Catches another specific exception named AnotherException.
except: Acts as a catch-all and catches any other exceptions not caught by the previous except blocks.

Note: you need to place your exceptions With a hierarchy from the most important to the least

Prepared by : Abdelaziz Shaheen


Try & Except

else: Contains code that executes only if no exceptions occur in the corresponding try block. It is optional.
finally: Contains code that always executes regardless of whether an exception occurred or not. It is optional.

Prepared by : Abdelaziz Shaheen


Try & Except

Prepared by : Abdelaziz Shaheen


Assignment

1. Write an advanced calculator


• Input example “7 + 5”
• The code should keep working
after ending the calculation
• The code could stop if the user
entered “stop,end,exit”

Prepared by : Abdelaziz Shaheen

You might also like