Advertisement



< Prev



Django Exception Handling





Similar to how we handle an exception in a Python program, we can use the try-except blocks to handle an exception thrown in a Django program. The try-except blocks are made up of two individual blocks - a try block and an except block.





The except block(preceded by an except keyword) declares a type of exception that it is going to catch and handle. If the type of exception declared in an except block is same as the type of exception thrown by try block, the exception is caught within this except block and the program continues its normal execution without ending abruptly.

Note: You may read extensively about Python try-catch.







What if we don't catch an exception using try-except blocks?


Exception thrown has a certain type. In order to catch an exception of a specific type, we have to make sure that our except block has declared the same type of exception that is thrown by the try block. But, if an exception occurs during the execution of a program which doesn't handle it, the exception halts the normal execution of the program and it ends abruptly.

Here's a quick example of a view function(and its associated urls.py). On executing this view function, it throws an exception and ends the program abruplty as it was not handled by try-except blocks.

views.py
# A view function with try-except block

def getdata(request):  
	a,b= 10,0
	# If a is divided by b(which has a value 0);
	c=a/b   			
		return HttpResonse(c)

urls.py
from django.urls import path
from . import views

urlpatterns = [
        path('form_submit/', views.getdata),  
]


Output :




As you can see in the output of the example, an exception of type ZeroDivisionError is thrown when a statement enclosed within the getdata view function is executed. This exception was unhandled and uncaught, hence, you saw the exception notification sent by Django.

But if the thrown exception of type ZeroDivisionError was handled by the try-except block, the program would not have ended abruptly. So let us show an how to handle an exception within a Django project.


Advertisement













Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON and DJANGO


Advertisement