All kinds of things cause errors, exceptions, and problems in programs. Exception handling is used to gracefully overcome these exceptions a program might encounter.
What is Exception Handling?
Incorrect syntax, incorrect user input, a server error, etc can cause errors. You have seen a few programs terminate because of errors. With exception handling, you can avoid letting errors interrupt program execution.
For this, Java makes use of five keywords. In the following sections, you will analyze the importance of each keyword.
Five Keywords for Exception Handling
try: A block of code. If anExceptionoccurs inside, theExceptionis thrown.catch: Used to catch and handle exceptions thrown in atryblock.throw: Used to manuallythrowanException.throws: Used to declare that a method maythrowone or some exceptions.finally: A block of code executed after atry, no matter what.
It might not be the biggest surprise that you're supposed to try to avoid and plan for errors, but what happens when this doesn't work?
What are Uncaught Exceptions?
When an Exception is not caught, it is the JVM's responsibility to handle the error. The issue is that the JVM defaults to terminating the program while printing the stack trace and error message when an Exception occurs, that is not caught or handled by your programs.
Uncaught Exception Example
Below is an example of an uncaught Exception printed in the console.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at NotHandled.main(NotHandled.java:9)
This information is often informative and can lead to the source of the issue. However, something other than what you want a user to see. You do not want an Exception like this to terminate the program.
The above Exception is generated when the program tries to access an index in an array that is "out of bounds". For instance, if you try to get the value at the index of 87 in an array that only has a length of 10. This is an ArrayIndexOutOfBoundsException. Catching an Exception like this would allow us to handle the situation gracefully and continue with the program. You will examine how to handle such exceptions and improve the usability of your code.
Summary: What are Java Exceptions?
- An
Exceptionin Java is a class that handles exceptions in your program Exceptionhandling is the process of predicting and preparing for exceptions in your program- Uncaught exceptions are errors that happen in a program and haven't been predicted by the developer
Five Keywords for Exception Handling
trycatchthrowthrowsfinally