Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Difference between Exception and Syntax Errors in Python
3.
Raising an exception
4.
Traceback
4.1.
Avoid raising generic exceptions.
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Raising an Exception

Author APURV RATHORE
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

When you work with complex programs, you may encounter some complicated bugs. In several cases, the time it takes to find and resolve the bug may exceed its time to write the whole program. There is no need to be discouraged. Even experienced programmers create bugs from time to time. 

During the application design process, you may find yourself in a situation where you don't know how to handle an error event in Python. Hence you may want to make your application throw an exception under certain circumstances. The act of raising or throwing exceptions is called exception raising. 

First, let us understand the difference between errors and exceptions in Python. 

Also See, Floor Division in Python and Convert String to List Python.

Difference between Exception and Syntax Errors in Python

The bugs in your program can be divided into syntax errors and exceptions. 

Syntax Error Exception
Arises when code does not follow the syntax rules  Arises due to some logical error in the program
Syntax error is found at compile time Exceptions are found at the runtime
Syntax errors are fatal, i.e., the program halts when it encounters a syntax error Exceptions are not fatal, i.e., they can be handled gracefully
If there is a syntax error in a program, there may also be an exception in the The syntaxprogram Program encounters an exception only when it passes syntax text, i.e., there is no syntax error

 

Must Read, leap year program in python

Recommended Topic, python packages

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Raising an exception

For error handling, you may wish Python to throw a custom exception. This may be accomplished by testing a condition and raising an exception if it is true. The user or calling program is notified when an exception is triggered.

To manually throw a Python exception, use the "raise" keyword. You may also include a message to explain why the exception occurred.

Example :


def fun(a,b,c,d):
    if b==0:
        raise Exception("Can't divide, the denomination is Zero")
    a = a//b 
    a += c 
    a+= b 
    return a

print(fun(1,0,3,4))

 

Output:

Traceback (most recent call last):
  File "d:\Course\Codeforces\New Codeforces\temp.py", line 9, in <module>
    print(fun(1,0,3,4))
  File "d:\Course\Codeforces\New Codeforces\temp.py", line 3, in fun
    raise Exception("Can't divide, the denomination is Zero")

 

In the above piece of code, we can see that a is getting divided by b. If b is zero, then it is a logical fault as a number cannot be divided by zero. Hence, we can manually raise an exception if such a case occurs.

Traceback

When Python encounters an error, it generates the traceback, which is a mine of error information. The error message, the line number of the line that created the error, and the sequence of function calls that lead to the error are all included in the traceback. 

Example:


def fun2():
    raise Exception('An exception occured')

def fun1():
    fun2()

fun1()

 

Output:

Traceback (most recent call last):
  File "d:\Course\Codeforces\New Codeforces\temp.py", line 7, in <module>
    fun1()
  File "d:\Course\Codeforces\New Codeforces\temp.py", line 5, in fun1
    fun2()
  File "d:\Course\Codeforces\New Codeforces\temp.py", line 2, in fun2
    raise Exception('An exception occured')
Exception: An exception occured

 

You can try it on online python compiler.

When you run the above piece of code, you will see an output similar to the above.

We can see that the error occurred on line 2 inside the fun2() function. This fun2() was called by fun1() in line number 5. The fun1() inturn was called by line 7. The traceback makes it easier to find where did the error occur and what was the error occurred, and the call stack, i.e., which functions were called before it.

Avoid raising generic exceptions.

When raising exceptions, avoid raising generic Exceptions. Instead, try to be as specific as you can while raising exceptions. For example, use 

raise ValueError(‘An error message’)

 

when you are sure that ValueError Exception will occur instead of 

raise Exception(‘An error message’)

 

You can also read about the Multilevel Inheritance in Python.

Frequently Asked Questions

  1. What is the difference between exceptions and errors?
    The problems in the program due to which the program is not able to complete its execution are called errors. In contrast, exceptions are raised due to some internal event that obstructs the normal flow of the execution. 
     
  2. Is there any way to write the traceback information to a text file?
    Yes, traceback.format_exc() function in the traceback module can be used to write the traceback information to a text file. For this, you have to import the traceback module into the program. 
     
  3. Which class is the base class of all exceptions?
    The class BaseException is the base class of all the exceptions. However, user-defined classes cannot inherit from this class. They need to inherit from the Exception class. 

Key Takeaways

Congratulations on making it this far.

In this blog, we understood Python's type-conversion and typecasting. 

If you want to become proficient with Python programming, I suggest you take the Coding Ninjas Python Course, which will teach Python basics with Data Structures and Algorithms. 

 

Previous article
Exception & Errors in Python
Next article
Catching an Exception in Python (try-except)
Live masterclass