DEV Community

Cover image for The Catch or Specify Requirement in Java
Tristan Elliott
Tristan Elliott

Posted on • Updated on

The Catch or Specify Requirement in Java

Introduction

  • This is the second post in my exception series. It will be on the Catch or Specify Requirement in Java's exception handling. No code in this tutorial, just understanding definitions.

The catch or specify Requirement in Java

  • To be able to write valid exception handling code in Java you must honor the catch or specify requirement. This means that we must deal with exceptions in 2 ways.

  • 1) try statement : the try statement catches the exception with an appropriate exception handler.

  • 2) throws statement : A method that specifies it can throw a exception must specify the throws clause in the method signature.

  • Any exception handling code in Java that fails to honor the catch or specify requirement when dealing with checked exceptions will not compile. If an exception is an unchecked exception, then it is not required to implement the catch or specify requirement. Checked and unchecked exceptions are better explained below.

3 types of exceptions in Java

  • 1) Checked exceptions : these are exceptions that your application should be able to recover from. Examples would be a file not existing or a bad input from an user. Check exceptions are subject to the catch or specify requirement. All exceptions are checked exceptions, not including Error and RuntimeException, along with their subclasses. Both Error and RuntimeException are considered to be unchecked exceptions.

  • 2) Errors : errors are a type of unchecked exception that happens externally to our application. These kinds of exceptions are ones our application usually can not recover from. Think hardware or system malfunction. Since errors are considered to be an unchecked exception, they do not follow the catch or specify requirement.

  • 3) Runtime Exceptions : these are exceptions that happen internally to our application. Things like programming bugs or a logic error made in the code. The most logical way to avoid this kind of exception is to make sure your code is properly tested. Runtime exceptions are also unchecked exceptions so they do not follow the catch or specify requirement.

Conclusion

  • Thank you for taking the time out of you day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.
  • Also make sure to checkout my YouTube channel for more programming tutorials

Top comments (0)