Java Checked and Unchecked Exceptions
- Details
- Written by Nam Ha Minh
- Last Updated on 09 July 2019   |   Print Email
In the article Java exception API hierarchy - Error, Exception and RuntimeException, you understand that Throwable is the supertype of all errors and exceptions in Java. Now we are going to understand what are checked exceptions and unchecked exceptions, and the differences between them.
Let’s review the exception API hierarchy:
1. What are Checked exceptions?
The exceptions that are subtypes of Exception (exclude subtypes of RuntimeException) are categorized as checked exceptions. When we use code that can throw checked exceptions, we must handle them, otherwise the compiler will complain.
For example, the following method can throw a checked exception of type IOException:
public void createFile(String path, String text) throws IOException { FileWriter writer = new FileWriter(path, true); writer.write(text); writer.close(); }
Then the caller code must handle this exception:
String filePath = "hello.txt"; String text = "Hello World"; try { createFile(filePath, text); } catch (IOException ex) { System.err.println("Error creating file: " + ex); }
See common checked exceptions in the section 3 below.
2. What are Unchecked exceptions?
In contrast, we don’t have to catch unchecked exceptions which are subtypes of Error and RuntimeException. Methods also don’t have to declare to throw unchecked exceptions. It’s because programs typically cannot be recovered from unchecked exceptions.
Note that unchecked exceptions are subtypes of RuntimeException, although it is a subtype of Exception.
For example, the following method does not have to declare to throw IllegalArgumentException which is an unchecked exception:
public static void setAge(int age) { if (age < 1 || age > 99) { throw new IllegalArgumentException("Invalid age"); } int newAge = age; }
Let’s see another example:
List<String> list = new ArrayList<>(); String item = list.get(3);
The get() method of the ArrayList class can throw IndexOutOfBoundsException but the code doesn’t have to catch because it is an unchecked exception.
See common unchecked exceptions in the section 4 below.
3. List of Common Checked Exceptions in Java
Common checked exceptions defined in the java.lang package:
- ReflectiveOperationException
- ClassNotFoundException
- InstantiationException
- IllegalAccessException
- InvocationTargetException
- NoSuchFieldException
- NoSuchMethodException
- CloneNotSupportedException
- InterruptedException
Common checked exceptions defined in the java.io package:
- IOException
- EOFException
- FileNotFoundException
- InterruptedIOException
- UnsupportedEncodingException
- UTFDataFormatException
- ObjectStreamException
- InvalidClassException
- InvalidObjectException
- NotSerializableException
- StreamCorruptedException
- WriteAbortedException
Common checked exceptions defined in the java.net package (almost are subtypes of IOException):
- SocketException
- BindException
- ConnectException
- HttpRetryException
- MalformedURLException
- ProtocolException
- UnknownHostException
- UnknownServiceException
Common checked exceptions defined in the java.sql package:
- SQLException
- BatchUpdateException
- SQLClientInfoException
- SQLNonTransientException
- SQLDataException
- SQLFeatureNotSupportedException
- SQLIntegrityConstraintViolationException
- SQLSyntaxErrorException
- SQLTransientException
- SQLTimeoutException
- SQLTransactionRollbackException
- SQLTransientConnectionException
- SQLRecoverableException
- SQLWarning
4. List of Common Unchecked Exceptions in Java
Common unchecked exceptions in the java.lang package:
- ArithmeticException
- IndexOutOfBoundsException
- ArrayIndexOutOfBoundsException
- StringIndexOutOfBoundsException
- ArrayStoreException
- ClassCastException
- EnumConstantNotPresentException
- IllegalArgumentException
- IllegalThreadStateException
- NumberFormatException
- IllegalMonitorStateException
- IllegalStateException
- NegativeArraySizeException
- NullPointerException
- SecurityException
- TypeNotPresentException
- UnsupportedOperationException
Common unchecked exceptions in the java.util package:
- ConcurrentModificationException
- EmptyStackException
- NoSuchElementException
- InputMismatchException
- MissingResourceException
Other Java Exception Handling Tutorials:
- 5 Rules about Catching Exceptions in Java
- Getting Started with Exception Handling in Java
- How to create custom exceptions in Java
- How to throw exceptions in Java - the differences between throw and throws
- Java exception API hierarchy - Error, Exception and RuntimeException
- Understanding Exception Stack Trace in Java with Code Examples
- Understanding Java Exception Chaining with Code Examples
- What you may not know about the try-catch-finally construct in Java
Comments
No, it's up to you to define your own error code number, by creating a custom exception class. Refer to this article: codejava.net/.../...
For Java Exception error, is there a number numeric error code allotted to each exception error like in many other programming language, or is it all text error messages ?