Python’s Errors and Exceptions

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
Structured programming
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exceptions COMPSCI 105 S Principles of Computer Science.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
The University of Texas – Pan American
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Python Conditionals chapter 5
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes.
Firoze Abdur Rakib. Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”
COMPSCI 107 Computer Science Fundamentals
C++ Exceptions.
Exceptions in Python Error Handling.
Introduction to Computing Science and Programming I
Topics Designing a Program Input, Processing, and Output
similar concepts, different syntax
George Mason University
Introduction to Python
Lecture 4 Python Basics Part 3.
Why exception handling in C++?
Presented By S.Yamuna AP/IT
Python - Functions.
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Exception Handling.
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
Chapter 3 – Control Structures
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Exceptions.
Programming in C# CHAPTER - 7
Python for Informatics: Exploring Information
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
Python Syntax Errors and Exceptions
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Advanced Python Concepts: Exceptions
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
By Ryan Christen Errors and Exceptions.
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Python Exceptions and bug handling
Dealing with Runtime Errors
Control 9 / 25 / 19.
Presentation transcript:

Python’s Errors and Exceptions Lakshay Puniani

Types of Errors There are two types of errors: Syntax Errors Exceptions

Syntax Errors Syntax Errors (Parsing Errors) are obtained during compilation. Example: >>> while True print 'Hello world' File "<stdin>", line 1, in ? while True print 'Hello world‘ ^ SyntaxError: invalid syntax When a syntax error is detected, the filename and line number are printed. The line is repeated and an arrow(^) is placed at the token where the error was detected.

Exceptions Exceptions are encountered during execution of the code. Exceptions are usually not handled by the program. If exceptions are not handled, the execution of the program is stopped and an error message is displayed. The filename and line number are displayed. Also displays the type of error and what caused it. There are many built in exceptions, but can also be user defined.

Exceptions (examples) >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 NameError: name 'spam' is not defined >>> '2' + 2 TypeError: cannot concatenate 'str' and 'int' objects

Handling Exceptions Try….except statements are used for handling exceptions. >>> while True: ... try: ... x = int(raw_input("Please enter a number: ")) ... break ... except ValueError: ... print "Oops! That was no valid number. Try again..." First, the try clause is executed. If no exception occurs, the except clause is skipped and execution of the try statement is completed. If an exception occurs, the except clause of the matching exception type is executed. The rest of the try clause is executed after this.

Handling Exceptions(cont.) If the exception does not match the type of the except clause, an error occurs. An except clause can have more than 1 type: ... except (RuntimeError, TypeError, NameError): ... Pass Exceptions can also be handled for functions. >>> def this_fails(): ... x = 1/0 ... >>> try: ... this_fails() ... except ZeroDivisionError as detail: ... print 'Handling run-time error:', detail ... Handling run-time error: integer division or modulo by zero

Else The else clause follows all except clauses. for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() If the except clause is not executed, else is executed. It is better to use else than writing more code in the try clause to avoid accidentally finding exceptions in the clause that were not expected.

Exception Variables If an exception has an associated value, this value can be stored in a variable. These variables are stored in instance.args. >>> try: ... raise Exception('spam', 'eggs') ... except Exception as inst: ... print type(inst) # the exception instance ... print inst.args # arguments stored in .args ... print inst # __str__ allows args to printed directly ... x, y = inst # __getitem__ allows args to be unpacked directly ... print 'x =', x ... print 'y =', y . … <type 'exceptions.Exception'> ('spam', 'eggs') x = spam y = eggs

Raising Exceptions A user defined exception can also be raised. >>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere Must be either an exception instance or an exception class.

Raising Exception(cont.) Exception can be raised inside a try block. >>> try: ... raise NameError('HiThere') ... except NameError: ... print 'An exception flew by!' ... raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in ? NameError: HiThere

User Defined Exceptions New exceptions can be defined by creating a new exception class. Exceptions should be derived from the exceptions class, either directly or indirectly. >>> class MyError(Exception): ... def __init__(self, value): ... self.value = value ... def __str__(self): ... return repr(self.value) ... >>> try: ... raise MyError(2*2) ... except MyError as e: ... print 'My exception occurred, value:', e.value My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): File "<stdin>", line 1, in ? __main__.MyError: 'oops!'

Clean Up Actions An exception can stop the execution of the try clause. Finally clause can be used after the try…except clauses. Finally clause is always executed, if an exception occurs or not. Finally clause can be used to close files that are left open or release resources that were allocated during execution.

Finally(example) >>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print "division by zero!" ... else: ... print "result is", result ... finally: ... print "executing finally clause" >>> divide(2, 1) result is 2 executing finally clause >>> divide(2, 0) division by zero! >>> divide("2", "1") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'

Predefined Clean Up Actions Some objects define standard clean-up actions to be taken when the object is no longer needed. >>>>for line in open("myfile.txt"): print line Prints each line in myfile.txt, but leaves the file open. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. >>>>with open("myfile.txt") as f: for line in f: After each with statement is executed, the file f is closed.

Questions?