Managing exceptions in Python: Difference between revisions

From Computer Science Wiki
No edit summary
 
(10 intermediate revisions by one other user not shown)
Line 1: Line 1:
[[File:idea.png|right|frame|This is basic programming knowledge <ref>http://www.flaticon.com/</ref>]]
==Introduction==
==Introduction==


The list type is a container that holds a number of other objects, in a given order. The list type implements the sequence protocol, and also allows you to add and remove objects from the sequence.<ref>http://effbot.org/zone/python-list.htm</ref>
Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. It is provided by specialized programming language constructs or computer hardware mechanisms.


Lists are a primitive [[data type]], very, very helpful for storing and changing data.
In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information. For example, a floating point divide by zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be resolvable transparently.


==Example of a function==
Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable such as C's errno or floating point status flags; or input validation to preemptively filter exceptional cases.


<syntaxhighlight lang="python" line="1" >
Some programmers write software with error reporting features that collect details that may be helpful in fixing the problem, and display those details on the screen, or store them to a file such as a core dump, or in some cases an automatic error reporting system such as Windows Error Reporting can automatically phone home and email those details to the programmers. <ref>https://en.wikipedia.org/wiki/Exception_handling</ref>


# creating a list is very easy. See below.
==Example exception handling in Python==


list_that_is_empty = []
<syntaxhighlight lang="python" line="1" >
list_of_computer_parts = ['mouse', 'keyboard', 'CPU', 'display']
try:
list_of_foods = ['kimchi', 'kielbasa', 'noodles', 'rice', 'pierogi']
    number = input("Enter a number ")
list_of_students =['joe','sally','frank']
    print("Your number was: " + str(number))
list_of_rooms = ['214a', '214b','212','211','210','209']
except NameError:
    print("Please use a number.")
</syntaxhighlight>


# here are the available methods available to a list:  
In the example above, if a user enters a string, for example 'abc', python would throw a NameError exception. This example was swiped from the official Python documentation which you should read.  <ref>https://docs.python.org/2/tutorial/errors.html</ref>


# list.append(x)
<syntaxhighlight lang="python" line="1" >
# Add an item to the end of the list;
# this code will generate a TypeError. We cannot concatenate a string and integer.  


# list.extend(L)
my_age = 16
# Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
try:
    print("Your age is " + my_age)  
except TypeError:
    print("Hey. You should know better than to combine strings and integers!")  
</syntaxhighlight>


# list.insert(i, x)
In the example above, we have been silly and tried to concatenate a string and an integer! We are testing for a specific type of exception, TypeError.
# Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).


# list.remove(x)
<syntaxhighlight lang="python" line="1" >
# Remove the first item from the list whose value is x. It is an error if there is no such item.
my_age = 16
 
try:
# list.pop([i])
    print("Your age is " + my_age)  
# Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
except Exception:
 
    print("Yikes. Something has gone horribly wrong.")  
# list.index(x)
</syntaxhighlight>
# Return the index in the list of the first item whose value is x. It is an error if there is no such item.
 
# list.count(x)
# Return the number of times x appears in the list.


# list.sort(cmp=None, key=None, reverse=False)
In our final example, above, we are using a generic test for any possible exception.
# Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).


# list.reverse()
== List of possible exceptions ==
# Reverse the elements of the list, in place.
</syntaxhighlight>


This example was swiped from the official Python documentation which you should read. <ref>https://docs.python.org/2/tutorial/datastructures.html</ref>
[http://www.tutorialspoint.com/python/python_exceptions.htm Please click here for a list of exceptions]


==References==
==References==


<references />
<references />
[[Category:This information is incomplete]]
[[Category:Python]]
[[Category:Exceptions]]
[[Category:Programming Basics]]

Latest revision as of 14:36, 18 May 2021

This is basic programming knowledge [1]

Introduction[edit]

Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. It is provided by specialized programming language constructs or computer hardware mechanisms.

In general, an exception is handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information. For example, a floating point divide by zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be resolvable transparently.

Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable such as C's errno or floating point status flags; or input validation to preemptively filter exceptional cases.

Some programmers write software with error reporting features that collect details that may be helpful in fixing the problem, and display those details on the screen, or store them to a file such as a core dump, or in some cases an automatic error reporting system such as Windows Error Reporting can automatically phone home and email those details to the programmers. [2]

Example exception handling in Python[edit]

try:
    number = input("Enter a number ")
    print("Your number was: " + str(number))
except NameError:
    print("Please use a number.")

In the example above, if a user enters a string, for example 'abc', python would throw a NameError exception. This example was swiped from the official Python documentation which you should read. [3]

# this code will generate a TypeError. We cannot concatenate a string and integer. 

my_age = 16
try:
    print("Your age is " + my_age)   
except TypeError:
    print("Hey. You should know better than to combine strings and integers!")

In the example above, we have been silly and tried to concatenate a string and an integer! We are testing for a specific type of exception, TypeError.

my_age = 16
try:
    print("Your age is " + my_age)   
except Exception:
    print("Yikes. Something has gone horribly wrong.")

In our final example, above, we are using a generic test for any possible exception.

List of possible exceptions[edit]

Please click here for a list of exceptions

References[edit]