throws Keyword

Declaring exceptions

4 min read

throws Keyword

The throws keyword declares exceptions that a method might pass to the caller.

Code Examples

Declaring checked exceptions

java
1
2void readFile() throws IOException {
3    FileReader fr = new FileReader("file.txt");
4}
5          

Use Cases

  • Delegating exception handling
  • API design

Common Mistakes to Avoid

  • Using throws everywhere
  • Not handling checked exceptions