Site icon TestingDocs.com

Mojo try-except block

Overview

Mojo try-except block allows you to gracefully handle exceptions or errors that might occur during the execution of the Mojo program. Let’s understand the concept with a simple example.

try-except block

The syntax of the try-except block is similar to Python.

Syntax
The general syntax is as follows:
try:
# code that might raise an error
except e:
# error handler code

 

Example

The program has a simple try block.

# Mojo try-except block
# Mojo Tutorials — www.TestingDocs.com

# main function
fn main() raises:
try:
raise Error(“!!”)
except e:
print(“An error has occurred”)

 

Save the code and run the Mojo code. Assuming the Mojo filename as try.mojo, type the following command to compile the code and run.

$ mojo try.mojo

The following output should be displayed:

An error has occurred

fn() raises syntax, which denotes that the function might raise an exception or error.

We can have that code inside the try block that could raise an error. In this example, we have explicitly raised an error for the demo. If the error is thrown, the execution in the try: block stops and the control
will reach the beginning of the except: block

The except: block provides the handler code for the error. Sometimes, we can fix the error or notify the user about it, etc. After handling the error, the execution continues with the first line after the except: block.

More information at Modular official website:

https://www.modular.com/

Exit mobile version