Mastering Java - Full Guide
Try Catch Exceptions
Try Catch ExceptionsWhen your program runs, sometimes unexpected problems occur. These problems are called exceptions. If you don’t handle them, your program will crash.
The try-catch block is how you safely handle exceptions in Java.
Basic Structure
The try-catch block lets you handle exceptions in a safe way. You put the “risky” code inside the try block. If something goes wrong, Java skips the rest of the try and runs the matching catch block instead. This prevents your program from crashing.
try {
// Code that might cause an exception
} catch (Exception e) {
// Code that runs if that exception happens
}The
tryblock contains the code that might throw an exception.If an exception occurs, the
catchblock runs.If no exception occurs, the
catchblock is skipped.You can have multiple
catchblocks for different exception types.Handling exceptions makes your program more stable.
Note: The Exception class is the parent of all exceptions in Java. If you write catch (Exception e), it will catch any kind of exception. This is useful as a backup, but it’s usually better to catch specific exception types so you know exactly what went wrong.
InputMismatchException
Let’s first look at the InputMismatchException. This exception occurs when we prompt the user for an input, and it does not match the type we are looking for. For example, if we use nextInt() from the Scanner class, and the user enters anything other than a whole number (like a decimal point 3.5 or a letter "abc"), Java will throw this exception and crash the program.

To prevent the program from crashing and receiving the error above, we can import InputMismatchException and use it as the specific exception type we want to catch. That way, the catch block will only run when an InputMismatchException occurs.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 14 more lessons in Mastering Java - Full Guide.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.