I am a C# developer doing occasional coding in Java. Can someone explain in simple terms what are checked exceptions in Java and why is it needed? Haven’t come across this term in C#.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Checked exceptions are exceptions that the compiler require you handle in some way.
In Java, checked exceptions are
Throwables that are notRuntimeException,Error, or one of their subclasses.The Java designers felt they were needed to ensure programs handled exceptions that were reasonably likely. A classic example is
IOException. Any time a program does I/O, there is a possibility of failure. The disk could be full, the file might not exist, there might be a permissions problem, etc.Thus, Java is designed such that a program must syntactically handle the exception in some way. This could be with a catch block, or by rethrowing the exception in some way.
C# does not have checked exceptions. They decided to leave this issue up to the application developers (interview). Checked exceptions are controversial because they can make code verbose, while developers sometimes handle them trivially with empty catch blocks. Further, it can be arbitrary which standard library methods throw checked exceptions. For instance, why doesn’t
File.delete(a new Java 7 API does this differently) throwIOException?Another concern Hejlsberg noted in that interview is versionability. Adding a checked exception to a
throwclause forces all code using that method to be modified and recompiled.