The following text is from "Effective Java", Item 2:
The traditional Abstract Factory implementation in Java has been the
Class object, with the newInstance method playing the part of the
build method. This usage is fraught with problems. The newInstance
method always attempts to invoke the class’s parameterless
constructor, which may not even exist. You don’t get a compile-time
error if the class has no accessible parameterless constructor.
Instead, the client code must cope with InstantiationException or
IllegalAccessException at runtime, which is ugly and inconvenient.
Also, the newInstance method propagates any exceptions thrown by the
parameterless constructor, even though newInstance lacks the
corresponding throws clauses. In other words, Class.newInstance breaks
compile-time exception checking. The Builder interface, shown above,
corrects these deficiencies.
Please go to this link for full text.
I've been able to follow everything before, "In other words..". Can someone please explain how does newInstance break compile-time exception checking and how does Builder pattern fixes it.
'newInstance' doesn't know ahead of time (at compile time) what exceptions could be thrown, as a normal class method would (because of the way code dependencies are built, and because a class has to make known which exceptions it throws).
The Builder pattern uses a class that takes a request (usually via a method) and creates a new object instance based on steps (most likely defined in that class).
Conceptually a non-abstract factory, and builder are very similar.
public class Main {
private int i;
public Main() throws IOException {
throw new IOException();
}
public static void main(String[] args) {
Class c = Main.class;
try {
c.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
In my opinion, if we use class.newInstance() method, we will never know the exactly exception will be thrown by the construction even though the exception is a checked exception and the checked exception isn't shown at the method signature. Just like the example above. If we use class.newInstance(), we will forget to handle the IOException and then get a "broken object". But the Builder pattern won't. Sorry for my pool english and hope you can understand.
Related
New Java programmers frequently encounter errors phrased like this:
"error: unreported exception <XXX>; must be caught or declared to be thrown"
where XXX is the name of some exception class.
Please explain:
What the compilation error message is saying,
the Java concepts behind this error, and
how to fix it.
First things first. This a compilation error not a exception. You should see it at compile time.
If you see it in a runtime exception message, that's probably because you are running some code with compilation errors in it. Go back and fix the compilation errors. Then find and set the setting in your IDE that prevents it generating ".class" files for source code with compilation errors. (Save yourself future pain.)
The short answer to the question is:
The error message is saying that the statement with this error is throwing (or propagating) a checked exception, and the exception (the XXX) is not being dealt with properly.
The solution is to deal with the exception by either:
catching and handling it with a try ... catch statement, or
declaring that the enclosing method or constructor throws it1.
1 - There are some edge-cases where you can't do that. Read the rest of the answer!
Checked versus unchecked exceptions
In Java, exceptions are represented by classes that descend from the java.lang.Throwable class. Exceptions are divided into two categories:
Checked exceptions are Throwable, and Exception and its subclasses, apart from RuntimeException and its subclasses.
Unchecked exceptions are all other exceptions; i.e. Error and its subclasses, and RuntimeException and its subclasses.
(In the above, "subclasses" includes by direct and indirect subclasses.)
The distinction between checked and unchecked exceptions is that checked exceptions must be "dealt with" within the enclosing method or constructor that they occur, but unchecked exceptions need not be dealt with.
(Q: How do you know if an exception is checked or not? A: Find the javadoc for the exception's class, and look at its parent classes.)
How do you deal with a (checked) exception
From the Java language perspective, there are two ways to deal with an exception that will "satisfy" the compiler:
You can catch the exception in a try ... catch statement. For example:
public void doThings() {
try {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
} catch (IOException ex) {
// deal with it <<<=== HERE
}
}
In the above, we put the statement that throws the (checked) IOException in the body of the try. Then we wrote a catch clause to catch the exception. (We could catch a superclass of IOException ... but in this case that would be Exception and catching Exception is a bad idea.)
You can declare that the enclosing method or constructor throws the exception
public void doThings() throws IOException {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
}
In the above we have declared that doThings() throws IOException. That means that any code that calls the doThings() method has to deal with the exception. In short, we are passing the problem of dealing with the exception to the caller.
Which of these things is the correct thing to do?
It depends on the context. However, a general principle is that you should deal with exceptions at a level in the code where you are able to deal with them appropriately. And that in turn depends on what the exception handling code is going to do (at HERE). Can it recover? Can it abandon the current request? Should it halt the application?
Solving the problem
To recap. The compilation error means that:
your code has thrown a checked exception, or called some method or constructor that throws the checked exception, and
it has not dealt with the exception by catching it or by declaring it as required by the Java language.
Your solution process should be:
Understand what the exception means, and why it could be thrown.
Based on 1, decide on the correct way to deal with it.
Based on 2, make the relevant changes to your code.
Example: throwing and catching in the same method
Consider the following example from this Q&A
public class Main {
static void t() throws IllegalAccessException {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
If you have been following what we have said so far, you will realise that the t() will give the "unreported exception" compilation error. In this case, the mistake is that t has been declared as throws IllegalAccessException. In fact the exception does not propagate, because it has been caught within the method that threw it.
The fix in this example will be to remove the throws IllegalAccessException.
The mini-lesson here is that throws IllegalAccessException is the method saying that the caller should expect the exception to propagate. It doesn't actually mean that it will propagate. And the flip-side is that if you don't expect the exception to propagate (e.g. because it wasn't thrown, or because it was caught and not rethrown) then the method's signature shouldn't say it is thrown!
Bad practice with exceptions
There are a couple of things that you should avoid doing:
Don't catch Exception (or Throwable) as a short cut for catching a list of exceptions. If you do that, you are liable catch things that you don't expect (like an unchecked NullPointerException) and then attempt to recover when you shouldn't.
Don't declare a method as throws Exception. That forces the called to deal with (potentially) any checked exception ... which is a nightmare.
Don't squash exceptions. For example
try {
...
} catch (NullPointerException ex) {
// It never happens ... ignoring this
}
If you squash exceptions, you are liable to make the runtime errors that triggered them much harder to diagnose. You are destroying the evidence.
Note: just believing that the exception never happens (per the comment) doesn't necessarily make it a fact.
Edge case: static initializers
There some situations where dealing with checked exceptions is a problem. One particular case is checked exceptions in static initializers. For example:
private static final FileInputStream input = new FileInputStream("foo.txt");
The FileInputStream is declared as throws FileNotFoundException ... which is a checked exception. But since the above is a field declaration, the syntax of the Java language, won't let us put the declaration inside a try ... catch. And there is no appropriate (enclosing) method or constructor ... because this code is run when the class is initialized.
One solution is to use a static block; for example:
private static final FileInputStream input;
static {
FileInputStream temp = null;
try {
temp = new FileInputStream("foo.txt");
} catch (FileNotFoundException ex) {
// log the error rather than squashing it
}
input = temp; // Note that we need a single point of assignment to 'input'
}
(There are better ways to handle the above scenario in practical code, but that's not the point of this example.)
Edge case: static blocks
As noted above, you can catch exceptions in static blocks. But what we didn't mention is that you must catch checked exceptions within the block. There is no enclosing context for a static block where checked exceptions could be caught.
Edge case: lambdas
A lambda expression (typically) should not throw an unchecked exception. This is not a restriction on lambdas per se. Rather it is a consequence of the function interface that is used for the argument where you are supplying the argument. Unless the function declares a checked exception, the lambda cannot throw one. For example:
List<Path> paths = ...
try {
paths.forEach(p -> Files.delete(p));
} catch (IOException ex) {
// log it ...
}
Even though we appear to have caught IOException, the compiler will complain that:
there is an uncaught exception in the lambda, AND
the catch is catching an exception that is never thrown!
In fact, the exception needs to be caught in the lambda itself:
List<Path> paths = ...
paths.forEach(p -> {
try {
Files.delete(p);
} catch (IOException ex) {
// log it ...
}
}
);
(The astute reader will notice that the two versions behave differently in the case that a delete throws an exception ...)
More Information
The Oracle Java Tutorial:
The catch or specify requirement
... also covers checked vs unchecked exceptions.
Catching and handling exceptions
Specifying the exceptions thrown by a method
I am using SonarQube and it shows the following error:
Public methods should throw at most one checked exception.
// Noncompliant
public void delete() throws IOException, SQLException { /* ... */ }
// Compliant
public void delete() throws SomeApplicationLevelException { /* ... */ }
Does this means, SomeApplicationLevelException is a parent class and IOException and SQALException are derived from it? And we should throw the parent class exception? Thereby adhering to method throwing only 1 checked exception?
Because I have 2 exceptions that i have defined say for example Exception1 and Exception2 that extend Exception. And my method say, sampleMethod() throws them i.e,
public void sampleMethod() throws Exception1, Exception2 {
}
And the error is shown here. So should I have one class as parent (say MainException) and derive Exception1 and Exception2 from it and throw parent exception class? Like below:
public void sampleMethod() throws MainException {
}
Is the above solution proper?
If you have a method in your application that is declared as throws SQLException, IOException, you are probably leaking internal implementation details to your method's users. Specifically, you're saying:
Your method is implemented using JDBC and file I/O. Your users don't care how your method is implemented; they only care about what your method does.
Your method, including any future version of it, will never throw any other checked exception. If in future you change your method so that it might throw another checked exception, it will break backwards compatibility.
The advice is to create your own application-specific class (derived from Exception), and only throw that in your method. You can, if you like, wrap the SQLException or the IOException (or any other exception) inside your application-specific exception as the cause.
Note, however, that there is a school of thought that says Java checked exceptions are a bad idea (and one of the reasons C#, and more modern languages such as Kotlin, don't have checked exceptions).
UPDATE: the above answer related to the first version of the question (edit #1). The question was subsequently updated to point out that the two thrown exceptions were application-defined ones, so therefore much of the above rationale no longer applies. The answer to the updated question is explained in this post.
IOexception and sqlexception both are checked exception s,totally different from each other , now if we extend both from one exception and throw the parent exception , which is not a mandatory in java, it will be kind of misguiding the user of the api.
However, if you want to do it in ur app to avoid sonarqube error , you can catch all your specific exceptions and throw a custom exception wrapping the original exception information in exception message.
for example
try{
///piece of code that throws IOException and SQLException
}catch(IOException | SQLException ex){
throw new DataException(ex,"Any customized message you want");
}
This DataException will then will be included in the throws clause of method signature having this try catch.
DataException extends Exception class and by passing ex in the contructor you are wrapping the original exception in custom exception with your original exception info preserved.
This is a simplified class that describes my problem:
public class Main {
enum Test{
First(method()){ // Unhandled exception type Exception
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
}
Above someCondition depends on device and some situations and I can not decide in about it now, also as you can see, I do not want to catch Exception in method.
Yes. It is a compilation error.
No. There is no special syntax to deal with this.
I do not want to catch Exception in method.
Unfortunately if you throw a checked exception, it has to be caught further up the call stack. That is a fundamental design principal for the Java language, and one that the compiler enforces strictly.
In this, case there is no way to catch the checked exception. Hence, if you are going to call a method in enum constant parameter (as per your code), the method cannot throw a checked exception1.
Here is a possible workaround, though this is probably a bad idea:
public class Main {
enum Test{
First(methodCatchingException()){
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
static Object methodCatchingException() {
try {
return method();
} catch (Exception ex) {
throw new SomeRuntimeException("the sky is falling!", ex);
}
}
}
Another way to look at this problem is to ask yourself what should happen with the exception if the compiler let you write that ... and an exception was thrown? Where would it go?
You can't catch it ... because the enum initialization is like a static initialization.
If the Java runtime completely ignored the thrown exception, that would be really bad.
If the Java runtime crashed, then the model of checked exceptions is broken.
So, what this is saying to me is that the Java language design is right, the Java compiler is right ... and the real problem here is in your application design:
You should not be propagating a checked exception here. If an exception occurs in this context it is categorically NOT a recoverable error.
Maybe it is inadvisable to use an enum for this ... because of the potential for non-recoverable initialization errors.
(Note that if this method call terminates due to an unchecked exception, it will turn it into an ExceptionInInitializerError. In addition, the JVM will mark the enum class as uninitializable, and will throw an NoClassDefFoundError if your application attempts to use it; e.g. via Class.forName(...).)
I assume that Exception is used here for illustration purposes. It is a bad thing to declare methods as throws Exception or to throw new Exception(...)
1 - I had a look at the JLS for something to back this up. As far as I can tell, the spec does not mention this situation. I'd have expected to see it listed in JLS 11.2.3. However, it is clear that a compiler cannot allow a checked exception to propagate at that point as it would "break" the model of how checked exceptions work.
I don't think you want to be throwing a checked exception here (which is what Exception is). The reason: you're invoking the call of method inside of the constructor of Test. There's really not a clean way to deal with it.
While the obvious choice here is to switch to RuntimeException, I want you to reconsider throwing the exception in the first place. Since your enum will only ever have First declared in it, does it really make sense for it to throw an exception when it's being instantiated? Personally, I don't think it does; whatever dangerous operation it's doing should be deferred until you want to invoke it, and then would you want to throw your exception.
According to this: https://docs.oracle.com/javase/tutorial/reflect/member/ctorTrouble.html
Class.newInstance() Throws Unexpected Exception
The ConstructorTroubleToo example shows an unresolvable problem in Class.newInstance(). Namely, it propagates any exception — checked or unchecked — thrown by the constructor.
This situation is unique to reflection. Normally, it is impossible to write code which ignores a checked exception because it would not compile. It is possible to wrap any exception thrown by a constructor by using Constructor.newInstance() rather than Class.newInstance().
Below I have a code that doesnt catch any unchecked (RuntimeEcxeption/Error) exception I commented them and it compiles. So where is this propagation? I wrote code that ignores unchecked exceptions which was told to be impossible. Please explain me what is wrong with Class.newInstance() regarding the above quotations?
try {
Class<?> c = Class.forName("ConstructorTroubleToo");
// Method propagetes any exception thrown by the constructor
// (including checked exceptions).
Object o = c.newInstance();
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException |
InstantiationException |
IllegalAccessException x
/*IllegalArgumentException |
SecurityException x*/ ) {
x.printStackTrace();
}
Class.newInstance() does indeed propagate any exception thrown by the constructor it calls, checked or unchecked. The propagation is done in a rather underhand way, by calling the method sun.misc.Unsafe.throwException(). This method, which simply throws the exception you give it, is part of the class sun.misc.Unsafe which contains various methods for low-level 'unsafe' operations in Java. This article summarises some of those methods.
In the JDK there is a src.zip file, which contains sources to some standard Java platform classes. In particular, you'll find the source to java.lang.Class within the file java/lang/Class.java in this zip. Open up this file and look at the newInstance() method within it. You'll find that Class.newInstance() actually uses Constructor.newInstance() to create the object.
If a constructor throws an exception, calling the constructor via Constructor.newInstance() will wrap the 'real' exception up in an InvocationTargetException and throw that. However, Class.newInstance() isn't declared to throw an InvocationTargetException, so instead it catches the InvocationTargetException thrown by Constructor.newInstance() and throws the 'real' exception instead, using Unsafe.throwException().
The reason that Class.newInstance() isn't declared to throw InvocationTargetException is because this method dates all the way back to Java 1.0. InvocationTargetException and the rest of the reflection API was introduced to Java in version 1.1. Adding throws InvocationTargetException to Class.newInstance() would have broken backwards compatibility when compiling Java 1.0 code with Java 1.1.
Propagation means that exception just goes out unlike wrapping into InvocationTargetException like reflection methods normally behave.
Actually it's not that impossible to write a code which ignores checked exception. Consider the first case from here:
public class Test {
// No throws clause here
public static void main(String[] args) {
doThrow(new SQLException());
}
static void doThrow(Exception e) {
Test.<RuntimeException> doThrow0(e);
}
#SuppressWarnings("unchecked")
static <E extends Exception>
void doThrow0(Exception e) throws E {
throw (E) e;
}
}
JVM does not distinguish checked and unchecked exceptions and there are some ways to fool the Java compiler.
I've been attempting to write Java exception handlers for a while now, have tried multiple methods and have even visited/read through Oracle's "The Java Tutorials" and I still cannot get it straight. I'm unsure what I am doing wrong. I have a given class (TooLowException) for the exception that I am trying to use. In the method I am attempting to use it in I am using an argument that I need to catch if it is less than zero.
public int func(int num) throws TooLowException {
int blah = num + 1;
if ( blah < 0) {
return blah;
}
else {
String error = "Input is too low.";
throw new TooLowException(error);
}
}
This is the exception class:
public class TooLowException extends Exception {
public TooLowException(String response) {
super(response);
}
}
I'm getting the error in Oracle "Unhandled Exception type TooLowException". I've also attempted the try-catch method as well, but it also doesn't work for me. Hopefully this is enough information for someone to point out what I'm doing incorrectly. I need to be set right in my ways of exception handling.
Taken from what info you've given, it seems that you need to have a try/catch block somewhere in your code. Basically somewhere in your application that func(int) method is being called, or needs to be called if you're running into a compiler error telling you the "Unhandled Exception type TooLowException." General rule for exceptions is Handle/Catch or Declare. This can be broken down like this:
Handle/Catch: If you choose to handle the exception, then the "throws" declaration should be removed from the method signature ("public int func(int num) throws TooLowException" becomes "public int func(int num)"). The idea behind this approach is that you as the programmer intend to handle this type of exception because it's specific enough to the method that you don't want external code to have to worry about handling the exception outside of the scope of the method. This requires that you "handle" the exception yourself, by using a try/catch block.
Declare: This is the method you went with. You are stating that whatever class uses this function has the burden of handling the exception with the try/catch block. This would be used if the method you wrote is generic enough that many different applications can use it and that handling the exception should be application specific, i.e., it's up to other developers to handle it in their own way. Some people like to just log things, others like to have a different control flow execute upon receiving certain exceptions.
Here's what works, sorry if it basically answers an exercise you needed to do, but it's in the interest of helping you! Please take time to understand what is happening here:
public class YourClassThisStuffIsIn {
public static int func(int num) throws TooLowException {
int blah = num + 1;
if ( blah < 0) {
return blah;
}
else {
String error = "Input is too low.";
throw new Exception(error);
}
}
public static void main(String[] commandlineArgument){
try {
YourClassThisStuffIsIn.func(3);
} catch (TooLowException tle){
System.out.println("Caught " + e);
}
}
}
When you click run in your IDE, or you run through the console, the JVM looks for the main method with the correct signature. In this case it finds it, and it executes the main method. First line is a try, meaning the JVM has to prepare itself for the possibility of a problem in the application, allowing it to recover in case an exception is thrown. In this case, the only exception that can be thrown is a TooLowException, which you have written how to handle it inside the catch block. Your way of handling it is simply printing the stack trace out, which is fine I think in this situation.
I've changed your example slightly, making your method static just so it's quicker to write. I also suspect that the intent is that the commandLineArgument is meant to be the number passed into the func(int) method, so in that case you're looking at the func method to look like func(Integer.parseInt(commandlineArgument[0])).
Bonus points for you is noticing that parseInt throws a NumberFormatException too, but you will of course remember that java.lang.RuntimeException and its subclasses aren't checked exceptions so there is no requirement to catch them, though it is good practice!