© Doug Winnie 2021
D. WinnieEssential Java for AP CompScihttps://doi.org/10.1007/978-1-4842-6183-5_34

34. Dealing with Errors

Doug Winnie1  
(1)
Mission Hills, KS, USA
 

When you introduce input from users, they won’t always provide input that is going to work for your program. When that happens, you need a way to have the program recognize that something is wrong and address it, without completely crashing.

When a program encounters an error, it “throws” it. You can then “catch” the error and do something with it, usually to provide some feedback for the user to know what they did wrong.

Coding to Catch Errors

To start, you need to wrap the code you think could cause an error. Begin with the try statement and create a code block, putting your code inside ...

Get Essential Java for AP CompSci: From Programming to Computer Science now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.