Reader small image

You're reading from  Solidity Programming Essentials. - Second Edition

Product typeBook
Published inJun 2022
PublisherPackt
ISBN-139781803231181
Edition2nd Edition
Concepts
Right arrow
Author (1)
Ritesh Modi
Ritesh Modi
author image
Ritesh Modi

Ritesh Modi is a technologist with more than 18 years of experience. He holds a master's degree in science in AI/ML from LJMU. He has been recognized as a Microsoft Regional Director for his contributions to building tech communities, products, and services. He has published more than 10 tech books in the past and is a cloud architect, speaker, and leader who is popular for his contributions to data centers, Azure, Kubernetes, blockchain, cognitive services, DevOps, AI, and automation.
Read more about Ritesh Modi

Right arrow

Chapter 8: Exceptions, Events, and Logging

Writing contracts is the fundamental purpose of Solidity. However, writing a contract demands sound error and exception handling skills. Errors and exceptions are the norms in programming, and Solidity provides ample infrastructure for managing both. Writing robust contracts with proper error and exception management is one of the requirements for any functional smart contract. Events are another important construct in Solidity. For all the topics that we've discussed so far, we've seen a caller that invokes functions in contracts; however, we have not discussed any mechanism through which a contract notifies its caller and others about changes in its state and otherwise. This is where events come in. Events are a part of event-driven programs where, based on changes within a program, they proactively notify their caller about the changes. The caller is free to use this information or ignore it. Finally, both exceptions and events...

Technical requirements

There are not many technical requirements for this chapter. The following will suffice for this chapter:

  • An operating system – Windows, macOS, and Linux would work equally well.
  • The Chrome browser for navigation to remix.org and writing smart contracts.

All code from this chapter can be found on GitHub at https://github.com/PacktPublishing/Solidity-Programming-Essentials-Second-Edition/tree/main/Chapter08.

Exception handling

Errors are a fact of life in the programming world. They are often inadvertently introduced while writing contracts and therefore writing error-free contracts is a desired skill. These errors can occur either at design time or runtime. Solidity is compiled into bytecode as part of compilation and the compiler checks for any syntax errors during this process. Runtime errors, however, are more difficult to catch and generally occur while executing contracts. It is important to test the contract for possible runtime errors, but it is more important to write defensive and robust contracts that take care of both design-time and runtime errors. Some examples of runtime errors are out-of-gas errors, divide-by-zero errors, data-type-overflow errors, and array-out-of-index errors.

Until version 4.10 of Solidity, there was a single throw statement available for error handling. Developers had to write multiple if...else statements to check the values and throw in the case...

Try-catch in Solidity

Solidity only had limited exception handling capabilities in the form of require, assert, and revert functions prior to version 0.6.0. Solidity introduced the much-needed try-catch functionality for implementing exception handling in contracts. The concept of try-catch is quite simple. There is a try block associated with a function call. This function should be an external function. If the called external function does not produce an error, the try block is executed. Execution of code in the try block means there have been no exceptions. Immediately following the try block is the catch block and the code within the catch block is executed in the case of revert (exception) from the target function. The try and catch blocks execution are mutually exclusive. Either the try block or catch block will get executed.

The syntax of try-catch is shown next:

Try <<function call>> returns (<<return values from 
  function call>>...

Events and logging

We have seen the use of events in previous chapters without going into any detail. In this section, however, we will look at events in more depth. Events are well known to event-driven programmers. Events refer to the notification of state change or an act of action in contracts to external entities such that they can react and take related actions.

Events help us to write asynchronous applications. Instead of continuously polling the Ethereum ledger for the existence of a transaction and then blocking with certain information, the same procedure can be implemented using events. This way, the Ethereum platform will inform the client if an event has been raised. This helps when writing modular code and also conserves resources.

It is to be understood that events do not directly associate themselves with any external entities. As we know that function execution in Ethereum happens much later while a block is getting added to the chain, the function cannot have...

Summary

In this chapter, we covered exception handling and events. These are important topics in Solidity, especially when writing any serious decentralized applications on the Ethereum platform. Exception handling in Solidity is implemented using three functions: assert, require, and revert. Although they sound similar, they have different purposes, which were explained in this chapter with the help of examples. Events help us to write scalable applications. Instead of continuously polling the platform for data and wasting resources, it's better to write events and then wait for them to execute functions asynchronously. This was also covered in this chapter. You will be able to use the skills learned in this chapter to add exception handling to your smart contracts, taking care of results arising out of unexpected environmental issues. Smart contracts allow you to notify in an asynchronous manner using logs and events when such an untoward incident happens.

In the next chapter...

Questions

  1. What are the keywords available in Solidity for exception handling?
  2. What keyword is used for raising an event from a contract function?
  3. Name two new error handling features in Solidity.

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Solidity Programming Essentials. - Second Edition
Published in: Jun 2022Publisher: PacktISBN-13: 9781803231181
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Ritesh Modi

Ritesh Modi is a technologist with more than 18 years of experience. He holds a master's degree in science in AI/ML from LJMU. He has been recognized as a Microsoft Regional Director for his contributions to building tech communities, products, and services. He has published more than 10 tech books in the past and is a cloud architect, speaker, and leader who is popular for his contributions to data centers, Azure, Kubernetes, blockchain, cognitive services, DevOps, AI, and automation.
Read more about Ritesh Modi