I have a fairly standard creational pattern whereby a class exposes a static method for returning instances of itself, like so:
public class MyClass {
private MyClass(/*parameter list*/) {
// internal construction
}
public static MyClass GetMyClass(/*parameter list*/) {
return new MyClass(/*parameter list*/);
}
}
...
//this line wont break in the debugger and seemingly never gets called - why?
MyClass inst = MyClass.GetMyClass(/*parameter list*/);
However, inst is always null. I can't break on the line that calls the static method, the debugger just ignores it - what's going on?
Edit: Thanks for the suggestions.
All projects have been cleaned and rebuilt (manully in NetBeans)
I have added a break in the static method and no it isn't hit.
Yes, the code above is being called (ultimately) in a constructor for a Swing 'FrameView' though it surely shouldn't matter where I am calling this from, should it?
There is no exception swallowing anywhere
Side note, other than the missing class declaration (which was a typo) why is this not valid Java? Why is this obviously C# code? Explanations would be more helpful than downvotes :)
Edit II: The Params is just supposed to indicate a whole load of parameters - sorry if this confused anyone, I obviously know parameters have type declarations and so on, the code above was intended as a quick shorthand version rather than a full and (complicated) real sample...
A couple of options:
An exception is being thrown which you're somehow missing
You're not debugging the code that you think you are (i.e. your built code is out of date with your source code)
The latter is the most likely one, IMO.
Apparently you're swallowing an exception inside the constructor something like:
try {
// Something.
} catch (Exception e) {
}
You should never do that. It makes debugging and nailing down the root cause much harder. Rather throw it or at least do a e.printStackTrace(). If throwing and you don't want to use the throws clause for some reasons, consider using a RuntimeException (or one of its subclasses). E.g.
try {
// Something.
} catch (Exception e) {
throw new RuntimeException("Construction failed.", e); // Try to be more specific, e.g. IllegalArgumentException or so. Or just write robust code, i.e. nullchecks and so on.
}
or (but in my opinion not very applicable in your case):
try {
// Something.
} catch (Exception e) {
e.printStackTrace();
}
I understand that you are trying to make a simple example to show your problem, however if you add the appropriate type statements into your sample code, then it both compiles and does what you expect.
However, in your original codebase you could simply place the breakpoint in the static method to see whether or not it is called.
Maybe a simple question, but you never know… are you sure that you are running the code that you think you are running? That is, is everything recompiled and built from the latest sources?
There is nothing wrong with :
MyClass inst = MyClass.GetMyClass(Params);
It depends what is before or after that line of code.
Start by doing this:
public class MyClass
{
private MyClass(/*parameter list*/)
{
System.out.println("entering MyClass(...)");
// internal construction
System.out.println("leaving MyClass(...)");
}
// Java uses lower case for method names - so get not Get
public static MyClass getMyClass(/*parameter list*/)
{
final MyClass foo;
System.out.println("entering getMyClass(...)");
foo = new MyClass(...);
System.out.println("leaving getMyClass(...)");
return (foo);
}
}
...
MyClass inst = MyClass.getMyClass(/*parameter list*/);
See if outside the debugger the code gets called.
If you are catching any exceptions, at the very least do:
catch(final WhateverException ex)
{
// at the very least do this so you can see that the exception happens
ex.printStackTrace();
}
Avoid catching Throwable, Error, Exception, and RuntimeException. Infact the best way do do it is get rid of all the catch statements and then only add catches for what the compiler tells you that you have to have.
The other thing is you do not say where MyClass inst = MyClass.getMyClass(/parameter list/); is called from. It is entirely possible that that line never gets hit.
You mention that you're calling this from the constructor of a FrameView, but I assume you're talking about an implementation or extension of that interface/object. My reasoning was to make sure you wern't recursively invoking the constructor.
I think the reason why catching java.lang.Exception isn't catching the problem is because it is likely too specific in this case. Try catching java.lang.Throwable which will catch errors like java.lang.NoClassDefFoundError - that frequently crops up when you have a jar missing somewhere.
Related
Up front: I'm a C# guy doing Java right now. Some of these frustrations come from my lack of knowledge of Java.
First, is there a way to have a "safe" AutoCloseable implementation that does not require the Exception to be checked? If I'm implmementing my own class that won't throw from its close method, I don't see why I have to check it.
Second, is there a way to simplify the expression in the try statement where I don't care what's returned? For instance in C# I can do this:
using (new Disposable())
{
// yay!
}
and Java seems to force me to assign it to a temporary variable:
try (AutoCloseable iDontCare = getAutoCloseable()) {
// dont you dare use iDontCare
}
I wish I could simplify the Java to
try (getAutoCloseable()) {
// yay!
}
C# isn't quite Java; this is one of those gotchas you'll have to deal with going forward.
First, is there a way to have a "safe" AutoCloseable implementation that does not require the Exception to be checked? If I'm implmementing my own class that won't throw from its close method, I don't see why I have to check it.
You have to because it's mandated by the interface. Not just that, but it throws a checked exception, which does have to be handled at some level.
If you know for a fact that your code will never throw any kind of exception, you could still place the throwing of the exception in some kind of guaranteed-not-to-be-executed-block inside of your implemented close method. Or, implement your own interface which extends AutoCloseable and overrides close to not throw an exception.
Your first question:
Yes. You can implement AutoCloseable.close without the throws Exception part if your implementation doesn't throw checked exceptions.
Your second question:
No. The try with resources statement requires that variable. You can rename it to something like ignored or unused to make that clear.
final class Test implements AutoCloseable {
#Override
public void close() {
System.out.println("Closing");
}
public static void main(String[] args) {
try (Test ignored = new Test()) {
System.out.println("Not using ignored");
}
}
}
Makoto's answer does a nice job of addressing the first part of your question, so I'll attempt to address the second.
I think what you want is a try (without resources). For example:
try {
//yay!
} finally {
// always executed
}
The finally block will execute regardless of whether an exception is thrown or not.
Edit:
If you don't need anything to execute, you could just declare a new block
{
//yay!
}
First of all I am not really sure what exactly the reason for this behaviour is, so the title might be wrong.
I have one "MainClass" which creates a new Object of a "SubClass" by using the Method.invoke() method (with a because there are several "SubClasses" all having the same method, if you a better way of solving this, I would appreciate it). As exceptions thrown by the invoke() method needs to be caught I have a try {} catch () {} around it. Now it seems like when one of the "SubClasses" throws an error and it is not directly in the code below a try block, it does not catch it but instead the "MainClass" catches it.
I don't know if this is the intended behaviour, but I would appreciate a way to prevent this from happening.
Example:
MainClass invokes method of SubClass
Method tries for example to do this new Gson().fromJson("Test",ArrayList.class); in a try block
MainClass catches the Exception
Apprently the problem was not Gson. What happeneds was that the
try {
new Gson().fromJson(...);
}
catch (Exception e) {
logThatError();
}
Correctly catched an Exception thrown by Gson but the logThatError() caused an Exception as well.
I've just started my very first toy-project in java and faced with misunderstanding of how it should be done. I'm using java.util.logging and JUnit4 library.
For example we have something like this:
public class SomeClass {
private static Logger log = Logger.getLogger(SomeClass.class.getName());
public static void SomeMethod() {
try{
...some code...
} catch(Exception e){
log.warning("Something bad happened");
}
}
And the unit-test will be:
#Test
public void SomeClassTest(){
SomeClass.SomeMethod();
}
But there will never be an exception, cause I've already handled it in method.
Should I generate new exception in catch-block? Or may be using junit combined with logging is not a good idea?
A method that does not throw an exception (and returns the expected value if any) is meant to work correctly from the perspective of a user.
So you should use try - catch and logging inside a method, when you can catch an exception and the method will still work correctly (do something else when this error happens for example but still return the expected result or perform the supposed operation).
In this case the unit test should check if the operation was performed correctly (if the object is in the expected state and the result value (in your case void) is correct
You should rethrow the exception (and usually not log it, but that depends) if the method cannot do what it is supposed to do when the exception occurs.
In this case the unit test should check if the operation was performed correctly (if the object is in the expected state and the result value (in your case void) is correct if there is no exception, and if there is an exception it should check if this exception was expected
If you want to test that the exception is thrown then you would have to re-throw, or not catch, the Exception.
Otherwise you can unit test that the class is in the correct state after the exception, i.e. that the exception was correctly handled.
I would say one other thing. Don't catch(Exception e), catch the specific exception you are expecting. Otherwise you will handle other, unexpected, exceptions in the same way and that is really quite dangerous.
You can simply rethrow the caught exception:
public class SomeClass {
private static Logger log = Logger.getLogger(SomeClass.class.getName());
public static void SomeMethod() {
try {
// your stuff
} catch (Exception e) {
log.warning("Something happened");
throw e;
}
}
}
Should I generate new exception in catch-block?
No. don't do that! you can test your existing code! when you only want to log the message but you don't want to handle it in the method that call someMethod() don't throw it!
using junit combined with logging is not a good idea?
both are good ideas and can be used together without problems.
Think about how you can test your method. i would not modify the code just that you can easily test it. because you WANTED to catch the exception and log for a reason.
try verifing what variables or objects are modified in your test-method
In my class I'm doing validation of custom data. Many conditions apply. Upon any failure, I want to throw a specific MyException. Throwing this MyException takes many common parameters, and one custom parameter (based upon the actual failure). So an actual throw takes many characters to write and destroys tidyness because of code duplication. Also I have to throw it too much times. I made up my mind to create a private method that prepares and returns a new instance of this MyException and takes the only custom data as parameter, so the code can be much cleaner.
private MyException createMyException(final CustomErrorData errorData)
{
... some info gathering, parameterizing, etc...
return new MyException(errorData);
}
...
So throwing a new MyException is much shorter:
throw createMyException(errorData);
My question is: what's the correct practice to prevent code duplication in this case? I may be overmistifying Exceptions.
An Exception factory - never seen it before but at least it sounds like a proper design.
I just worry - you seem to put quite a lot effort on designing an exception throwing framework: adding parameters, states, etc. to exceptions. Do you really encounter that many exceptional conditions in your code? Or do you throw exceptions where proper handling of expected conditions would?
Usually a thrown exception is "just for the logs". Something happened that shouldn't have happened in the current context. Something, the developers should know and correct in the next release. We shouldn't use exceptions to handle expected states.
So before investigating in brilliant exception creation code, double-check if it's worth the effort or if the design of your application is starting to get ... too creative.
If you have one general type of exception you will lose some of the advantages of OOP.
Instead of being able to have try-catch for specific exception types you will have to have a catch for your general exception and then continue processing based on some fields inside your MyException class.
You will have something like this:
try{
//code here
}
catch (MyException ex){
switch(ex.exceptionType){
case IOException: doSomething();break;
case ConnectionException:doSomethingElse();break;
default: //throw the exception outwards if you don't want to process it
}
}
When instead you should have something like
try{
//code here
}
catch (IOException ex){
doSomething();
}
catch (ConnectionException ex){
doSomethingElse();
}
which is more clear and more OOP.
Why you would place all your exceptions under a general type is something of a puzzle, it's like making all your objects to be instances of only one class, but you would require of them different behaviors based on some flags.
Imho your helper function is perfectly fine, i dont see another approach that would be preferable here..
I would throw the exception in the method, unless this confuses the compiler.
private void throwMyException(final CustomErrorData errorData) {
... some info gathering, parameterizing, etc...
throw new MyException(errorData);
}
throwMyException(errorData);
or
private MyException throwMyException(final CustomErrorData errorData) {
... some info gathering, parameterizing, etc...
throw new MyException(errorData);
}
throwMyException(errorData);
// or if the compiler complains
throw throwMyException(errorData);
I'd separate the two concerns. Your class knows how to info gather, but shouldn't have to know about the exception (the user of that info).
First define a method to create a CustomErrorData instance:
private CustomErrorData createCustomErrorData() {
// info gathering
return new CustomErrorData(something);
}
Then define a constructor for the exception that uses a CustomErrorData:
public MyException(CustomErrorData errorData) {
// save it as a field
}
then
throw new MyException(createCustomErrorData());
where you need it.
This also allows you to use CustomErrorData for something else, perhaps logging, displaying to the user, whatever.
In my unit test, I test a method for an expected RuntimeException and I want to distinct those thrown by my component from ones thrown by the code called in the method.
Creating a custom exception type is unnecessary and does not solve the problem if the method throws the same exception type but for different reasons, e.g. InvalidArgumentException.
Looks like the only way to tell them is the message or the error code. Because the message can be changed during development, the error code seems the only reliable option.
What is the best practice for creating of system of error codes so they don't conflict with ones of external packages, eg. third party libraries?
Creating a custom exception type is unnecessary and does not solve the
problem if the method throws the same exception type but for different
reasons, e.g. InvalidArgumentException.
Why do you think it's unnecessary? This is what you should do. Derive your own custom exception classes, throw their instances from your code and catch them outside (in your unit tests). The catch statement can be repeated in anticipation of multiple different exception classes:
try {
// something
} catch (MySpecificException e) {
// you know that your code threw this
} catch (Exception e) {
// this is coming from somewhere else
}
--Edit--
Sorry, I didn't see the java tag. Even though the following example uses PHP constructs, the principles should still apply.
--Original--
I use custom exception codes in only a few, very specific cases, and I store these codes in a custom exception class which extends the default exception class. They are stored in the class as constants, as the value doesn't really matter, but the context does.
Consider:
class CoreLib_Api_Exception extends Exception
{
const EXCEPTION_FORMAT = '%s (%s): %s';
const CODE_FILE_DNE = 100;
const CODE_DIR_BASE_EQUALS_REMOVE = 101;
const CODE_XML_READER_UNABLE_TO_OPEN = 200;
const CODE_XML_READER_UNABLE_TO_READ = 201;
}
// Example usage
class CoreLib_Api_Reader
{
protected function getReader()
{
$reader = new CoreLib_Api_Xml_Reader();
if (!#$reader->open($this->getFileUri())) {
$e = new CoreLib_Api_Exception(sprintf('Could not open %s for parsing', $this->getFileUri()), CoreLib_Api_Exception::CODE_XML_READER_UNABLE_TO_OPEN);
throw $e;
}
}
}
// Calling code
try {
$reader = CoreLib_Api_Reader();
$reader->setFileUri($fileUri);
$reader->getReader();
} catch (Exception $e) {
// If code is anything other than open, throw it
if ($e->getCode() !== CoreLib_Api_Exception::CODE_XML_READER_UNABLE_TO_OPEN) {
throw $e;
}
$e = null;
$reader = null;
}
By using the exception code, I can check to determine if the reader is unable to open the file, if so ignore the exception and move on, otherwise throw the exception and break the flow.
And if one of my exception codes collides with a third party exception code, it doesn't matter, as I mentioned before, using constants, the context will dictate which code I want to match on.
I test a method for an expected RuntimeException
I think this is a mistake. A RuntimeException should be used only for indicating bugs in the code that the code itself can detect. Testing should test only for specified (defined) behaviour. But when there is a bug in some code, its behaviour is undefined (who knows where the bug could be or what it might do). So there is no point in trying to specify what RuntimeExceptions some code should throw; that is like specifying how the code should behave "in the presence of a bug". Throwing particular RuntimeExceptions with particular messages should be seen as a courtesy to the maintenance programmer (who is likely to be you).