Working with Exceptions

Learn what are exceptions and how to work with them.

What is an exception?

An exception (short for exceptional event or exceptional condition) is an error or an unexpected event that occurs while a program is running. It’s caused by a condition in the software where the program has reached a state where it can no longer run.

There are many reasons we can get an exception. One example could be if our program needs to read data from a file, but the file is not where it’s supposed to be. Since the program has a reason to read the data from this file, a failure to do so will put the application in a state where it can no longer guarantee that its output will be correct. The best option, in this case, is just to halt the program and give back an error that hopefully instructs us about what the problem is so we can fix it.

No software developer wants to write an application that crashes. It can make the users of the application lose unsaved work, though the consequences might be even worse, depending on the nature of the program.

Soon, we’ll talk about how we can handle exceptions so that they don’t crash our program. But before we do that, let’s explore exceptions a bit so that we have an understanding of how they work. Let’s take a look at some common reasons we get exceptions.

Common reasons for exceptions

As we saw, a missing file can be one reason we get an exception. Another common reason is that when we’re trying to index into a sequence, we use an index that’s larger than the sequence. Let’s take a look at an example:

Get hands-on with 1200+ tech skills courses.