Min menu

Pages

Error in Python

 

 Errors in Python

Error handling Exceptions Handling ) It is intended to write code that may cause any problem in the program in a way that ensures that if the expected error or any other error occurs, the program will not hang or close suddenly.

The sudden appearance of an error in the program is very bad because it alienates a large number of users and their unwillingness to return to using this program again.

 

Types of errors in Python 

  • Errors appear while writing the code. These errors are called grammatical errors Syntax Errors ).

  • Errors occur during the operation of the program, which leads to its suspension and stopping abnormally. These errors are called exceptions Exceptions ).

  • logical errors Logical Errors ), It means that the code works without any problems, but the result of running this code is incorrect.

So, any software error that occurs with you while running the program is called an exception Exception ) Even if the error name contains the word Error.
In other words, any Error It appears to you while the program is running Exception.

In this lesson, you will learn how to avoid errors in the programs you write, and actually you will learn how to prepare the program to deal with errors that may occur during its operation so that the program is always running in the eyes of the user and does not show him any errors.



Some of the reasons that cause an exception in Python

  • If you enter a number index Not found in an array or in a text variable.

  • In the event that the program connects to the network and suddenly the connection is cut off.

  • If the program is trying to read information from a text file, and this file does not exist.

Examples of types of errors in Python


Example with a grammatical error Syntax Error )

In the following example, we put an extra parenthesis for the print function, since we wrote  print()) instead of print().

Example

Test.py
x = 10
		  print(x))
	

We will get the following result when we run the file Test.

File " C:/Users/Mhamad/PycharmProjects/myapp/Test.py ", line 2
    print(x))
            ^

SyntaxError: invalid syntax

Important note about syntax errors in Python

a program PyCharm It puts you a red error that shows you exactly where there is a language error before you run the program.
If you run the program without fixing the error, you will find that the Python interpreter also puts a red arrow  ^  telling you where you found a syntax error in the code when trying to execute it.



 Examples of bugs Exceptions )

In the following example we have printed the value of a variable that we did not originally give a value for!
Note:  Here the runtime error will occur when the Python interpreter detects that the variable does not contain a value.

first example

Test.py
print(x)
		

We will get the following result when we run the file Test.

File " C:/Users/Mhamad/PycharmProjects/myapp/Test.py ", line 1, in <module>

NameError: name 'x' is not defined

In the following example, we have defined  list his name aList, It consists of  4  elements.
Then we tried to print the value of each element in it and we tried to print the value of an element that does not exist!
Note:  Here the runtime error will occur when the Python interpreter detects that there is no object that owns Index equals  4  in the object aList.

second example

Test.py
# It consists of 4 aList elements named list. Here we have defined
		  aList = [10, 20, 30, 40]
	  
		  # list Here we have printed the values ​​of the object's elements
		  print(aList[0])
		  print(aList[1])
		  print(aList[2])
		  print(aList[3])
	  
		  # This will cause a runtime error list Here we have printed the value of an element that does not exist in the object
		  print(aList[4])
	

We will get the following result when we run the file Test.

10
20
30
40
File " C:/Users/Mhamad/PycharmProjects/myapp/Test.py ", line 8, in <module>
    print(aList[4])

IndexError: list index out of range


Example with a logical error Logical Error )

In the following example, we created a program that prints for the student whether he passed or failed based on his final grade.
It is assumed that a student will be considered failing if his GPA is between  0  and . 9.9 . And it is considered successful if its average is  10  and 20 .
The logical error we set is that when printing the student's result we didn't check if the rate was between  0  as a minimum and  20 as a  maximum.

Example

Test.py
average = 25
	  
		  if average < 10:
		  print('The student failed the exam')
	  
		  elif average >= 10:
		  print('The student passed the exam')
	

We will get the following result when we run the file Test.

The student passed the exam

We note that there is no software problem that caused the code to stop, but we know that there is a logical problem in the code.
The logical problem here is that the rate at which the success statement is printed is impossible to be true.

Camel  try and  except and  finally and  else in Python

We use these sentences for the following reasons:

  • Any code that you suspect may cause an error must be placed inside the sentence block  try to ensure that the program does not get stuck or suddenly appear during operation.

  • Any code you want to implement to handle the error that occurred in the sentence, you  try put it inside the sentence block  except.

  • Any code you want to implement if there is no error in the sentence, you  try put it inside the sentence block  else.

  • Any code you want to implement, whether or not an error occurred in the sentence, you  try put it inside the sentence block  finally.



important information 

Once you put the code inside you  try will be forced to put the sentence  except or the sentence  finally after or both.
As the program PyCharm You will see an alert as soon as you put the code inside telling you that  try you should put one of these two sentences after it.

After the sentence,  except you can put a sentence  finally or a sentence  else if you want, but you can't put both at the same time.

In the event that you are writing code that can cause several types of problems, you can put more than one sentence  except to address each type of problem that may occur separately.


So if you want to use strings  try and  except and  finally the code will look like this.

try:
		#Something
		except:
		# Handle Errors
		finally:
		# Optional Clean Up Code
  


So if you want to use strings  try and  except and  else the code will look like this.

try:
		#Something
		except:
		# Handle Errors
		else:
		# If No Errors, Do Extra Things
  


In the following example, we used the two  statements try and  except did not put any intentional error in the code.
Remember:  since no error occurs within the sentence  try , it means that no command placed in the sentence will be executed except.
Then the execution of any commands placed in the program will be completed.

first example

Test.py
x = 10
	  
		  # except Since there is no problem here, it means that the print command placed in the x statement will not be executed. We tried to print the try value in the statement
		  try:
		  print('x =', x)
		  except:
		  print('An exception occurred')
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

x = 10
Program still working


In the following example  , we used the two statements try and  except put an intentional error in the code.
Remember:  since an error will occur within the sentence  try , this means that the sentence will be moved to  except when the error occurs.
After that, the orders placed in it will be executed, and then the execution of any orders placed in the program will be completed.

second example

Test.py
# which we haven't stored any value in yet. Since this will throw an x ​​error, we try to print the try value in the sentence
		  # and execute any command placed in it except and move to the try sentence, this means that the sentence will be exited
		  try:
		  print('x =', x)
		  except:
		  print('An exception occurred')
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

An exception occurred
Program still working


In the following example  , we used the two statements try and  except put an intentional error in the code.
Note:  Here we expected a specific error and the possibility of any other error.

third example

Test.py
# which we haven't stored any value in yet and therefore x error will occur We tried to print the try value in the sentence
		  try:
		  print('x =', x)
	  
		  # The following code will be executed - NameError if the cause of the error is an attempt to return the value of a variable that was not previously defined - i.e. an error of type
		  except NameError:
		  print('x is not defined')
	  
		  # The following code will be executed - NameError if the cause of the error is an error of any other type - other than the type
		  except:
		  print('An exception occurred')
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

x is not defined
Program still working


In the following example, we used the three sentences  try and  except and  finally and did not put any intentional error in the code.
Remember: any command placed in the  sentence  finally is executed whether or not an error occurred.

Fourth example

Test.py
x = 10
	  
		  try:
		  print('x =', x)
	  
		  except:
		  print('An exception occurred')
	  
		  # try will be executed if an error occurs or not in the finally statement whichever command is placed in the sentence
		  finally:
		  print('Finally block always executed')
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

x = 10
Finally block always executed
Program still working


In the following example, we used the three sentences  try and  except and  else and did not put any intentional error in the code.
Remember: the  sentence  else only performs any command placed in it, whether or not an error has occurred.

Fifth example

Test.py
x = 10
	  
		  try:
		  print('x =', x)
	  
		  except:
		  print('An exception occurred')
	  
		  # try is executed only if there is no error in the else clause, the commands we put in the sentence
		  else:
		  print('Else block executed only when no exception occurred')
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

x = 10
Else block executed only when no exception occurred
Program still working

 Ready exceptions in Python

Basic exceptions or errors in Python are divided into several types, and each type is represented in a special class.
All of these classes inherit from a basic class named BaseException.
This means that if you want to define your own exception in the future, you will have to create a class that inherits from this class or from one of the classes that inherit from it.

So, any class that inherits from the class  BaseException is a class that represents a certain exception.

BaseException
		+-- SystemExit
		+-- KeyboardInterrupt
		+-- GeneratorExit
		+-- Exception
		+-- StopIteration
		+-- StandardError
		| +-- BufferError
		| +-- ArithmeticError
		| | +-- FloatingPointError
		| | +-- OverflowError
		| | +-- ZeroDivisionError
		| +-- AssertionError
		| +-- AttributeError
		| +-- EnvironmentError
		| | +-- IOError
		| | +-- OSError
		| | +-- WindowsError (Windows)
		| | +-- VMSError (VMS)
		| +-- EOFError
		| +-- ImportError
		| +-- LookupError
		| | +-- IndexError
		| | +-- KeyError
		| +-- MemoryError
		| +-- NameError
		| | +-- UnboundLocalError
		| +-- ReferenceError
		| +-- RuntimeError
		| | +-- NotImplementedError
		| +-- SyntaxError
		| | +--IndentationError
		| | +-- TabError
		| +-- SystemError
		| +-- TypeError
		| +-- ValueError
		| +-- UnicodeError
		| +-- UnicodeDecodeError
		| +-- UnicodeEncodeError
		| +-- UnicodeTranslateError
		+-- Warning
		+-- DeprecationWarning
		+-- PendingDeprecationWarning
		+-- RuntimeWarning
		+-- SyntaxWarning
		+-- UserWarning
		+-- FutureWarning
		+-- ImportWarning
		+-- UnicodeWarning
		+-- BytesWarning
  

Print the error message that occurred in Python

When an error occurs in the sentence try, The Python interpreter creates an object representing the type of error that occurred in this statement.
Then it passes over each sentence  except placed after it, and compares the type of object that was created in the sentence  try with the type of error (which is originally the name of the class that represents the error expected to occur) that each  except sentence deals with until it finds the sentence that addresses this type of error and executes The commands placed therein.

Now, if you want to print the error message that occurred in the syntax  try , which in turn sent it to the syntax  except , all you have to do is receive the error message from this object and put it in a variable with the keyword as.



The following example teaches you how to print the ready-made error message into the object that represents the specific error that might occur.

first example

Test.py
# Because we tried to print the value of a variable that does not have a value at all, the NameError code here causes an error of type
		  try:
		  print('x =', x)
	  
		  # And then display msg The ready-made error message will be stored in this object and temporarily placed in the variable NameError Here we said that any error of its type
		  except NameError as msg :
		  print('Error Message:', msg)
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

Error Message: name 'x' is not defined
Program still working


The following example teaches you how to print the ready-made error message, whatever type of error occurred in the sentence try.
Note:  We have repeated the same example as the previous one, with the class replaced  NameError by the  classBaseException.
The basic idea here is that since the class  BaseException is the primary class for any error that may occur, this means that we can consider the error that occurred as an object of it because it would be of a class that inherits from it.

second example

Test.py
# Because we tried to print the value of a variable that does not have a value at all, the NameError code here causes an error of type
		  try:
		  print('x =', x)
	  
		  # And then display msg The ready-made error message will be stored in this object and temporarily placed in the variable NameError Here we said that any error of its type
		  except BaseException as msg :
		  print('Error Message:', msg)
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

Error Message: name 'x' is not defined
Program still working

keyword  raise in python

If you want to build a function that throws an exception in the event of a certain error, all you have to do is make this function  work raise for a class object  Exception containing the error message you want to show.



In the following example, we built a function that throws an exception if a value less than  0 is passed to  it when called.
Then we called the function and passed a value less than  0  to it, causing the program to stop.

first example

Test.py
# Takes a value when called func Here we have defined a function whose name is
		  # If a value less than 0 is passed to it, an exception is thrown. Otherwise it prints the value passed to it
		  def func(x):
		  if x < 0:
		  raise Exception("Error: Passed value can't be negative")
	  
		  print(x, "Acceptable value")
	  
	  
		  # and pass a value greater than 0 to it. We notice that it prints it and that does not cause any problem in the code func() here we called the function
		  func(5)
	  
		  # and pass a value smaller than 0 to it. We note that this command caused a problem in the code and led to stopping the func() program. Here we called the function
		  func(-1)
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

5 Acceptable value
File " C:/Users/Mhamad/PycharmProjects/myapp/Test.py ", line 14, in <module>
    func(-1)
File " C:/Users/Mhamad/PycharmProjects/myapp/Test.py " , line 5, in func
    raise Exception("Error: Passed value can't be negative")

Exception: Error: Passed value can't be negative


In the following example, we built a function that throws an exception if a value less than  0 is passed to  it when called.
Then we called the function inside a block  try , passing a value less than  0  to it, and then treating the error it would cause inside the block. except.

second example

Test.py
# Takes a value when called func Here we have defined a function whose name is
		  # If a value less than 0 is passed to it, an exception is thrown. Otherwise it prints the value passed to it
		  def func(x):
		  if x < 0:
		  raise Exception("Error: Passed value can't be negative")
	  
		  print(x, "Acceptable value")
	  
	  
		  # twice func() here we tried to call the function
		  try:
		  func(5)
		  func(-1)
	  
		  # Here we catch any error that may occur because the value passed to the function is less than 0, and then print the error message
		  except Exception as msg:
		  print(msg)
	  
	  
		  # The next print command will be executed if the program does not have any problem or there was a problem previously and it was fixed
		  print('Program still working')
	

We will get the following result when we run the file Test.

5 Acceptable value
Error: Passed value can't be negative
Program still work