Question

I need help explaining this question and code: The try-except statements are helpful in handling errors...

I need help explaining this question and code: The try-except statements are helpful in handling errors that are detected during execution. What are the two categories of errors when debugging code? How can the try-except statements handle errors in Python? Provide a code example that supports your comments...Thanks in advance

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The two categories of errors when debugging code:

  1. Compile time errors
  2. Runtime time errors

1.Compile time errors

Answer: When we write any code, our source code file is given to a program called ‘compiler’. Compiler checks whether everything written in a file is correct or according to the rules specified by that programming language. Rules are-> how we are suppose to write code. For example: declaring variables, initializing them, writing functions. Let’s see the following example to understand this better:

  1. In C++ programming language function is written in following way:

Type function_name([type variable])

{

//Function body;

}

Eg.:       int addition(int a, int b)

{

               return (a+b);

}

  1. In Python function is written in following way:

def function_name([variable]):

               #function body

E.g.:     def addition(x,b):

                              print(x+b)

So, as we can see for different programming languages there is a different way to write a function. And if do some mistake while writing them, then at the time of compilation an error would get generated saying ‘incorrect syntax’. This is because the compiler checks whether everything is syntactically correct. So, what can go wrong at compile time: 1) Syntax errors, 2) type checking errors.

E.g.:       string a=”hello”

int b=a

     In above case, we are trying to assign a string type value to an integer type variable. So there is a type checking error.

2. Runtime errors

Answer: If the program is correct for the compiler and there is no compile time error, then program is now passed for the execution to the interpreter in Python. The program may exit unexpectedly during execution if it encounters a runtime error – a problem which was not detected when the program was parsed, but is only revealed when a particular line is executed.

Runtime errors are generated due to:

  1. Divide by zero operation
  2. Accessing array element which does not exists
  3. Trying to open a file which is not present

For example:

               A=10

               B=0

               C=A/B

               print (c)

In above example, no compile time error is generated because for compiler, everything is syntactically correct. But while execution interpreter finds it semantically incorrect as we are trying to divide ‘A’ by 0. So, the exception of divide by zero would get generated.

try-except statements:

To deal with exceptions try-except can help us.

               try : this block contains the code which may generate an exception.

               except : this block contains the code to handle the exception.

E.g.: If we write a program where we are using a variable without declaring it before. We will try this a) without try-except and b) with try-except

a) without try-except

In [1]: print(x) Name Error Traceback (most recent call last) <ipython-input-1-fc17d851ef81> in <module> ----> 1 print(x) Nam

As we can see, print(x) is trying to print the value of variable which is not declared or initialized before. So program is generation error and has stopped it’s execution.

b) with try-except

In [2]: try: print(x) except: print(An exception occurred) An exception occurred

When we write the statement which may generate an exception in a try block. Then when such statement is executed the program control is passed to the ‘except’ block. And statements from except block get executed. Hence, it avoids the abnormal interruption in the program.

See following example:

  1. Division by zero without try-except:

def divide_operation(a,b): C=a/b; print(Result of, a,/,b, is: ,c) print(End of the program) divide_operation (10,0) -

As we can see, as program has stopped abnormally , it is not printing the line ‘End of the program’.

  1. Division by zero with try-except:

def divide_operation(a,b): try: C=a/b; print(Result of,a,/,b, is: ,) except: print(Please dont pass second parameter

Even if exception occurred, ‘End of the program’ gets printed in the screen.

Below is code in the screenshot :

def divide_operation(a,b):
try:
c=a/b;
print("Result of",a,"/",b," is: ",c)
  
except:
print("Please don't pass second parameter as zero")
print("End of the program")

divide_operation(10,0)

def divide_operation(a,b): try: C=a/b; print(Result of,a,/,b, is: ,) except: print(Please dont pass second parameter

Add a comment
Know the answer?
Add Answer to:
I need help explaining this question and code: The try-except statements are helpful in handling errors...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Chapter 08 Python Assignment: Question 1-5 Please I need help in my python course. Question 1...

    Chapter 08 Python Assignment: Question 1-5 Please I need help in my python course. Question 1 The finally clause of a try statement a. can be used to recover from an exception b. is required c. can be used to display more information about an exception d. is executed whether or not an exception has been thrown 10 points Question 2 Which of the following is the correct way to code a try statement that catches any type of exception...

  • 12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try...

    12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try the code and catch the errors. The other paradigm is 'Look before you leap' which means test conditions to avoid errors. This can cause race conditions. 1.Write the output of the code here: class MyError(Exception): pass def notZero(num): if num == 0: raise MyError def run(f): try: exec(f) except TypeError: print("Wrong type, Programmer error") except ValueError: print("We value only integers.") except Zero Division Error:...

  • I am required to use the try - catch block to validate the input as the...

    I am required to use the try - catch block to validate the input as the test data uses a word "Thirty" and not numbers. The program needs to validate that input, throw an exception and then display the error message. If I don't use the try - catch method I end up with program crashing. My issue is that I can't get the try - catch portion to work. Can you please help? I have attached what I have...

  • I need help wring a python code for my IOT class. This code will be used...

    I need help wring a python code for my IOT class. This code will be used on Tinkercad I am to create a Blinking LED and Ultrasonic Senor For this project you will be creating a distance sensor circuit with visual feedback. You will use a Ultrasonic sensor to measure the proximity. An LED will be used to indicate the proximity on an object by blinking fast to close objects, and slow for far away objects. You can use your...

  • use python IDEL Please highlight the answer 1 ווCIוסטIT Errors and Exceptions. There are two main...

    use python IDEL Please highlight the answer 1 ווCIוסטIT Errors and Exceptions. There are two main types of errors: syntax errors and runtime errors. Syntax errors are detected by the Python interpreter before the program execution during the parsing stage (parsing is a process, during which the Python interpreter analyzes the grammatical structure of the program). Runtime errors are errors in a program that are not detected by the Python interpreter during its parsing stage. They are further divided into...

  • Hi, I need help writing a code for this. The language is python 3, and we...

    Hi, I need help writing a code for this. The language is python 3, and we cannot use things like break, continue, exit(), lambda, map, filter, raise, try, except, and assert in our code. Thank you! We must write a function called "binary_to_decimal(binary_number)" that takes a string for a binary number and output the decimal integer for that number. The solution, aka the code, MUST contain a for loop of this form (power is an integer variable you define earlier):...

  • Hi I need some help writing a security code using python mongodb restful api. I just...

    Hi I need some help writing a security code using python mongodb restful api. I just need help on how to provide a security login to user to enter their username and password or to have a block in using extra access once they have logined and they want more access to the databases they will be force to sign out of the server but I just do not know how to start on it can someone show me how...

  • I need help with this assignment. Please include comments throughout the program. Thanks Develop an algorithm...

    I need help with this assignment. Please include comments throughout the program. Thanks Develop an algorithm and write the program in java for a simple game of guessing at a secret five-digit code. When the user enters a guess at the code, the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 13720, and the user guesses 83521, the...

  • I need help with this problem please, This code needs to be in Ruby, Java, or...

    I need help with this problem please, This code needs to be in Ruby, Java, or Python. See problem below. -5 - Functional Programming (due Mon] Assignment Content Your software company was invited to provide a proposal for a company in Australia. You currently have the cost in US dollars and need to convert the prices to the Australian dollar. Write a 2-part program using Ruby, Java, or Python. Part 1: Write a function to gather the following costs from...

  • Hi, I need help writing a code for this. The language is python 3, and we...

    Hi, I need help writing a code for this. The language is python 3, and we cannot use things like break, continue, exit(), lambda, map, filter, raise, try, except, and assert in our code. Thank you! Implement one of the sorting algorithms from class, either bubble, selection or quick sort with the following modification. Call the function "color_sort(the_list)" Each element is now a list (or tuple) with two elements. The first element is the number value that you need to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT