Could you tell me can be some case when exception is throwing in constructor and object is not null. I mean some part of object is created and another is not.Like this
public Test(){
name = "John";
// exception
// init some other data.
}
I understand in this sitiation object Test will be null, but Can be situation that object test cannot be null (delete block of exception not answer :) ) ?
A class instance creation expression always creates a new object if the evaluation of its qualifier and arguments complete normally, and if there is space enough to create the object. It doesn't matter if the constructor throws an exception; an object is still created. The class instance creation expression does not complete normally in this case, though, as it propagates the exception.
However, you can still obtain a reference to the new object. Consider the following:
public class C {
static C obj; // stores a "partially constructed" object
C() {
C.obj = this;
throw new RuntimeException();
}
public static void main(String[] args) {
C obj;
try {
obj = new C();
} catch (RuntimeException e) {
/* ignore */
}
System.out.println(C.obj);
}
}
Here, a reference to the new object is stored elsewhere before the exception is thrown. If you run this program, you will see that the object is indeed not null, though its constructor did not complete normally.
No. Look at the client code:
Test myObj = null;
try {
myObj = new Test();
} catch(MyException e) {
System.out.println("" + myObj);
}
Here, when exception occurs, the '=' operation is not executed. Your code goes straight to the catch block and myObj stays null.
No. If exception occurs during the instantiation of the object, it will not be created.
Anyway, you would you write it?
MyObject obj = new MyObject();
// This code will not be reachable in case of an Exception
or:
MyObject obj = null;
try {
obj = new MyObject();
} catch (AnyException e) {
}
// Here, either obj is created correctly, or is null as an Exception occurred.
public Test() {
name = "John";
try {
// exception
// init some other data.
} catch(AnyException e) {
// catch
}
}
The above code makes sense as per your expectation.
Related
For user code, there are a couple of options for correctly closing multiple resources:
1. try-with-resources
try (
A a = new A();
B b = new B();
C c = new C()
) {
// ...
}
Apart from being nice and short, it is also correct.
It will correctly close whichever of a, b and c needs closing.
Additionally, it will also "suppress" exceptions which occur during close if exception is thrown from the body (this is an improvement over try/finally as can be read here https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)
2. Guava Closer
For pre-JDK7 there is Guava's Closer which is used like:
Closer closer = Closer.create();
try {
A a = closer.register(new A());
B b = closer.register(new B());
C c = closer.register(new C());
// ...
} catch (Throwable e) { // must catch Throwable
throw closer.rethrow(e);
} finally {
closer.close();
}
While slightly longer, it also works pretty good (check here https://github.com/google/guava/wiki/ClosingResourcesExplained#closer for more info)
What about objects holding multiple resources?
Say I have:
public class P implements AutoCloseable {
private A a;
private B b;
private C c;
public P() {
a = new A();
b = new B();
c = new C();
}
public close() {
c.close();
b.close();
a.close();
}
}
There are multiple problems with this code:
If exception is thrown from the constructor, nothing will be closed (the caller does not have the instance on which to call close)
If exception is thrown from close, some resources will not be closed
Neither 1 nor 2 suffered from these issues. However:
try-with-resources obviously cannot be used, as lifetime of P is controlled by the caller
Guava Closer seems cannot be used either. While it is more flexible, it does not support close-and-rethrow, which is necessary from the constructor
What is the correct pattern here for N resources without too much boilerplate? The solution should also have the suppression property of 1 and 2
If exception is thrown from the constructor, nothing will be closed (the caller does not have the instance on which to call close)
You can catch any Exception that is thrown during the initialization of the individual resources and close all the resources initialized so far and throw back one Exception denoting initialization failed.
If exception is thrown from close, some resources will not be closed
Same as above, but this time it denoting closing of some resources failed.
This solution makes the below assumption:
If you take your original code snippet having a try with resources with three resources A, B and C,
if initialization of any of those failed or the try block throws an Exception and
the close method of one or more of them throws an Exception,
then only the Exception thrown from 1 is thrown back and the exception(s) from 2 is suppressed and can be obtained by calling the Throwable's getSuppressed.
However, when you are abstracting the individual resources with a wrapper class, I don't believe we must have the same behaviour i.e, adding close method failures (exceptions) to suppressed exceptions. In other words, all those resources must be abstracted by the wrapper and must not throw any exception specific to one resource.
The entire initialization code is wrapped in a single try..catch block. If any of the resource initialization fails, it closes all the opened resources and throws back one Exception to denote that the initialization of the wrapper resource failed. If any of the close fails here, it is silenced (and cannot be obtained via getSuppressed by the caller).
When closing the wrapper resource, each of the individual resources are closed and if any of them fails, again one Exception denoting the closing of the wrapper resource failed is thrown back.
Let Resources be the class that holds multiple closeable resources.
public class Resources implements AutoCloseable {
private MyCloseable1 myCloseable1;
private MyCloseable2 myCloseable2;
public Resources() {
try {
myCloseable1 = new MyCloseable1();
myCloseable2 = new MyCloseable2();
} catch (Exception e) {
close(false, myCloseable1, myCloseable2);
throw new RuntimeException("Initialization failed");
}
}
#Override
public void close() throws Exception {
close(true, myCloseable1, myCloseable2);
}
private void close(boolean throwExceptionIfFailed, AutoCloseable... autoCloseables) {
boolean closeFailed = false;
for (AutoCloseable autoCloseable : autoCloseables) {
try {
if (autoCloseable != null) {
autoCloseable.close();
}
} catch (Exception e) {
//Add logs here.
closeFailed = true;
}
}
/*
Using Java 8 streams and reduce.
closeFailed = Arrays.stream(autoCloseables)
.filter(Objects::nonNull)
.reduce(false, (isFailed, autoCloseable) -> {
try {
autoCloseable.close();
} catch (Exception e) {
return true;
}
return isFailed;
}, (isFailed1, isFailed2) -> isFailed1 || isFailed2);
*/
if (closeFailed && throwExceptionIfFailed) {
throw new RuntimeException("Closing of Resources failed");
}
}
}
Usage:
try (Resources resources = new Resources()) {
....
} catch (Exception e) {
....
}
I would suggest doing this:
public close() throws ... {
try (A aa = a;
B bb = b;
C cc = c) {
// empty
}
}
We are simply using the standard try-with-resource mechanism to close the resources that were opened previously. This will deal with the cases where a, b or c are null, and where the close() calls throw an exception.
For the constructor:
public P() throws ... {
try {
a = new A();
b = new B();
c = new C();
} finally {
if (!(a != null && b != null && c != null)) {
close();
}
}
It is more complicated if you want to suppress exceptions thrown by close() in the constructor.
You can hide opening and closing of resources from your resources wrapper class' users with execute around method pattern. This way you will ensure resources will always be closed. You should add separate operation methods for different use-cases. This will only be usefull if this is a common resource and used by many part of the application.
Here is a sample
public class ResourceWrapper {
private A a;
private B b;
private C c;
private ResourceWrapper() {
// add try catch if you have to, after cleanup then throw exception if ithappens
a = new A();
b = new B();
c = new C();
}
/**
* add required operation methods
*/
public ResourceWrapper op1() {
// do some operations
return this;
}
public ResourceWrapper op2() {
// if additional add or different
return this;
}
// close everything here
private void close() {
// check null if you have to
// add try catch if you have to
c.close();
b.close();
a.close();
}
public static void use(Consumer<ResourceWrapper> consumer) {
ResourceWrapper resource = null;
try {
resource = new ResourceWrapper();
consumer.accept(resource);
}
finally {
if(resource!=null) {
resource.close();
}
}
}
}
public class SampleResourceUser {
/*
* This represents the user of the Resource,
* User only cares about which operations that needs to be done on the resource.
* Opening and closing the resource wrapped around the operation methods by the owner of the Resource.
*
*/
public static void main(String[] args) {
ResourceWrapper.use(resource->resource.op1().op2());
}
}
Can someone help me to understand why java is trying to make an instance of a before b. And also, why it is looping between line 2 and line 3?
public class Winterfell {
private Winterfell a= new Winterfell();
public Winterfell() throws Exception {
throw new Exception("Fire and Ice");
}
public static void main(String[] args) {
try {
Winterfell b = new Winterfell();
System.out.println("Surprise!");
} catch (Exception ex) {
System.out.println("I told you so");
}
}
}
This will cause a StackOverflowError.
By having a field referencing a new object of the same class or by making a new object of the same class in the constructor you have an infinite number of calls to create a new Winterfell object.
That is why it is looping.
To fix this you likely want to remove private Winterfell a= new Winterfell(); so that a single Winterfell object is created.
private Winterfell a= new Winterfell();
Is invoked prior to invoking the constructor of Winterfell because it's a data member. Check out the Oracle documentation for object construction for more info.
I have created Exception xml and dynamically create and throw exception.
<exception-mappings>
<exception-mapping key="exceptionkey1">
<class-name>com.package.CheckedException</class-name>
<message>Checked Exception Message</message>
</exception-mapping>
<exception-mapping key="exceptionkey2">
<class-name>com.package.UnCheckedException</class-name>
<message>UnChecked Exception Message</message>
</exception-mapping>
I create object of exception dynamically using reflection depending on the exception key.
public static void throwException(final String key) throws CheckedException, UncheckedException {
ExceptionMapping exceptionMapping = exceptionMappings.getExceptionMappings().get(key);
if (exceptionMapping != null) {
try {
Class exceptionClass = Class.forName(exceptionMapping.getClassName());
try {
throw ()exceptionClass.newInstance(); // line X
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I want to know which class to typecast at line X so that I do not need to use If/else. Reason behind I do not want to use if else is, it may be possible that in future, there may be new classes added and I do not want to change this code every time new exception is added.
My base logic is my service layer will throw either CheckedException or UncheckedException. If CheckedException is thrown, it will be handled by my web layer. Also I can not throw Super parent class Exception or Throwable as my web layer only catch CheckedException. If UncheckedException is thrown, it will display exception page.
Please help me as I am not able to proceed further.
EDIT: Any other solution is also accepted.
Well, in the name of science, here's how you can do it. Would I recommend doing this? By no means. Would I ever do anything remotely like this myself? Probably not.
public class ExceptionFactory {
public static void throwException(String className)
throws CheckedException, UncheckedException {
Class<?> exceptionClass;
try {
exceptionClass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
try {
if (CheckedException.class.isAssignableFrom(exceptionClass)) {
throw exceptionClass.asSubclass(CheckedException.class)
.newInstance();
} else if (UncheckedException.class
.isAssignableFrom(exceptionClass)) {
throw exceptionClass.asSubclass(UncheckedException.class)
.newInstance();
} else {
throw new IllegalArgumentException(
"Not a valid exception type: "
+ exceptionClass.getName());
}
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
public static void main(String... args) {
try {
throwException("CheckedException");
} catch (CheckedException e) {
System.out.println(e);
} catch (UncheckedException e) {
System.out.println(e);
}
}
}
class CheckedException extends Exception {
}
class UncheckedException extends Exception {
}
I don't see the point of this factory. Even if you get it to work (which you can by having all the exceptions thrown by it being sub-classes of a single ancestor class), its usage would be something like this :
....
if (somethingInWrong) {
ExceptionFactory.throwException("SomeKey");
}
....
For each key you'd still have to create an exception class to be mapped to it. Lets say SomeKeyException is the exception mapped to "SomeKey".
In that case, it's much more type safe to simply write :
....
if (somethingInWrong) {
throw new SomeKeyException();
}
....
This way the compiler checks that you are creating an exception class that it actually knows. If you use your Factory, you might use some String that is not a valid key, and the compiler won't be able to do anything about it. Only in runtime your Factory will fail to find an exception mapped to the invalid key.
There's no need to use reflection (as I commented above you shouldn't use reflection unless you really have to...).
You can implement the exceptions class to be something like this:
class MyExceptions {
static void myExceptionsThrower(String key) throws Exception {
if("illegalstate".equals(key)) {
throw new IllegalStateException("that's my IllegalStateException bro!");
}
else if("illegalaccess".equals(key)) {
throw new IllegalAccessException("that's my IllegalAccessException bro!");
}
// etc...
}
}
and use it with:
MyExceptions.myExceptionsThrower(key);
A few tweaks:
public static void throwException(final String key) throws Throwable {
ExceptionMapping exceptionMapping =
exceptionMappings.getExceptionMappings().get(key);
if (exceptionMapping != null) {
try {
Class<Throwable> exceptionClass =
(Class<Throwable>)Class.forName(exceptionMapping.getClassName());
try {
throw exceptionClass.cast( exceptionClass.newInstance() ); // line X
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Here's my entry into this derby. :-)
The other answers have commented on whether this is a reasonable design. I'll set these issues aside for the purpose of this answer.
A couple of my pet peeves are unnecessary warnings (even if suppressed), and exceptions that don't report what actually went wrong. In particular merely printing out a stack trace is usually insufficient. Yes, this is just test code, but when dealing with code like this -- even code that's designed to throw an exception -- one really ought to think about how to deal with errors. In this case I've chosen to represent these kinds of errors as instances of InternalError since the configuration or whatever can be wrong in a variety of ways. Specifically: if the class can't be found, if it is found but isn't a subtype of CheckedException or UncheckedException (or even an ordinary class), or if doesn't have a no-arg constructor or if it's inaccessible.
Another issue with some of the proposed solutions is that if the exception class name is "java.lang.InstantiationException" (or one of the other internally-caught exceptions) an instance of this exception type might be constructed, thrown, and then caught internally, resulting in a stack trace but not actually throwing the requested exception. I've avoided that by linearizing the logic instead of nesting try-catch blocks.
Finally, I extracted the exception-creating code into a separate method so that it can be used for both the checked and unchecked cases. This can be simplified considerably if you rearrange the exception hierarchy to allow only a single root exception (I recommend unchecked) and have exception subtypes that are handled at the web layer or are thrown out to the caller.
static void throwException(final String exClassName) throws CheckedException, UncheckedException {
Class<?> clazz;
try {
clazz = Class.forName(exClassName);
} catch (ClassNotFoundException cnfe) {
throw new InternalError(exClassName, cnfe);
}
if (CheckedException.class.isAssignableFrom(clazz)) {
throw newException(clazz.asSubclass(CheckedException.class));
} else if (UncheckedException.class.isAssignableFrom(clazz)) {
throw newException(clazz.asSubclass(UncheckedException.class));
} else {
throw new InternalError(exClassName + " is not a valid exception");
}
}
static <X extends Throwable> X newException(Class<X> clazz) {
X x;
try {
x = clazz.newInstance();
} catch (InstantiationException|IllegalAccessException e) {
throw new InternalError("creating instance of " + clazz, e);
}
return x;
}
This could be helpful to create a custom precondition exception to avoid multiple if conditions.
Creates a precondition exception while checking for null pointer.
class Preconditions {
/**
* <p>
* Checks the value to be null and if null throws a new Exception with the message given.
* Used to reduce checking if conditions for complexity.
* </p>
* #param val - val to check null
* #param exceptionClass - exception class to be thrown
* #param args - message to be called for throwing exception
* #throws Throwable - Common Throwable Exception.
*/
public static void checkNotNull(final Object val, final Class<?> exceptionClass, final Object ...args) throws Throwable {
Class<?>[] argTypes = new Class<?>[args.length];
Arrays.stream(args).map(WithIndex.indexed()).forEach(arg ->argTypes[arg.index()] = arg.value().getClass());
if (null == val) throw (Throwable) exceptionClass.getConstructor(argTypes).newInstance(args);
}
}
Then you can use it in code with:
PreConditionUtil.checkNotNull(objectToCheck, CustomException.class, ErrorCode, "your error message", ...);
I have some code with this structure:
public void method() {
Object o;
try {
o = new Object();
} catch (Exception e) {
//Processing, several lines
throw new Error(); //Our own unchecked exception
}
doSomething(o);
}
I have quite a few methods in which I have the same code in the catch block, so I want to extract it to a method so that I can save some lines. My problem is, that if I do that, I get a compiler error "
The local variable o might not have been initialized".
public void method() {
Object o;
try {
o = new Object();
} catch (Exception e) {
handleError();
}
//doSomething(o); compiler error
}
private void handleError() throws Error {
//Processing, several lines
throw new Error();
}
Is there any workaround?
You need to initialize local variables before they are used as below
public void method() {
Object o=null;
try {
o = new Object();
} catch (Exception e) {
handleError();
}
doSomething(o);
}
You will not get the compilation failure until you use local variable which was not initialized
Since o is getting initialized within the try block and initializing o might throw an exception, java thinks that doSomething(o) statement might reach without o being initialized. So java wants o to be initialized incase new Object() throws exception.
So initializing o with null will fix the issue
public void method() {
Object o = null;
try {
o = new Object(); //--> If new Object() throws exception then o remains uninitialized
} catch (Exception e) {
handleError();
}
if(o != null)
doSomething(o);
}
Initialize your object: Object o = null;, however watch out for the NullPointerExceptions that might be thrown when you give it to the method calls.
Just put the doSomething(o) inside the try { } block:
public void method() {
Object o;
try {
o = new Object();
doSomething(o);
} catch (Exception e) {
handleError();
}
}
You perhaps dont want to execute doSomething() if the creation of your Object fails!
Instance variable is the Object type so you should initialize value "null"
public void method() {
Object o=null;
try {
o = new Object();
} catch (Exception e) {
handleError();
}
doSomething(o);
}
It happens because compiler doesn't know if handlerError always throws the Error. For example, there can be a logic in handleError method that makes it returns before throwing exception.
If you want to extract error handling into method, you can do this in this way:
public void method() {
Object o;
try {
o = new Object();
} catch (Exception e) {
throw handleError();
}
System.out.println(o);
}
private Error handleError() {
//Processing, several lines
return new Error();
}
Now the compiler sees the throw word in catch block, and it is sure that the exception will be thrown.
I'm trying to have the file "TutorialMap" used as the map in this TutorialMission. I keep getting told that the MapReader "reader" needs to be static, but when it's static, I get told "Unhandled exception type FileNotFoundException" with the error on the constructor of reader.
static MapReader reader = new MapReader("TutorialMap");
static Territory[][] missionMap = reader.getMap();
public TutorialMission() throws FileNotFoundException {
super(missionMap, Size, AircraftCarrierID, AircraftCarrierID);
}
The Super class' constructor:
public class MissionIF extends Map {
public MissionIF(Territory[][] load, String size, int StartingMoney, int powerLevel)
{
// Set money per mission.
super();
Thanks for your time.
I don't know why it must be static, but since the constructor throws the checked exception, it has to be handled at the place of calling. Therefore do something like this:
static MapReader reader = null;
static Territory[][] missionMap = null;
static {
try {
reader = new MapReader("TutorialMap");
} catch(FileNotFoundException e) {
e.printStackTrace();
}
missionMap = reader.getMap();
}
Compiler requires your reader to be static because you invoke it when initializing other static variable missionMap.
When you mark it as static compiler is going forward and sees that you do not catch exception thrown from your constructor TutorialMission.
Since I do not understand what do you really want to do I can just suggest you:
If you want all this stuff to be static initialize reader into static initializer and catch exception:
static MapReader reader;
static {
try {
reader = new MapReader("TutorialMap");
} catch(FileNotFoundException e) {
throw new IllegalArgumentException(e);
}
}
Your checked exception is now wrapped by unchecked one.
Alternatively (if you do not really want to hold this data in static variables just remove static modifier and perform initalization in constructor:
public TutorialMission(MapReader reader, Territory[][] missionMap) throws FileNotFoundException {
super(missionMap, Size, AircraftCarrierID, AircraftCarrierID);
missionMap = reader.getMap();
}
Now caller is responsible on creating and passing here the reader.
surrounds the code throwing "Unhandled exception type FileNotFoundException" with try catch block. Your are getting this exception because its a checked exception and you are forced to handle this. i would suggest using IDE like eclipse(if you are not using this already) which is really helpful for development.
try {
reader = new MapReader("TutorialMap");
} catch(FileNotFoundException e) {
throw new RunTimeException(e);
}