Java: Too high value handling - best practice? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is both a specific and a fundamental question:
I am reading a value from a configuration file and it must be higher than some X or else I won;t be able to run my program correctly.
In case the value is lower than X...
Is it a correct practice to throw an exception in that case?
If yes - Should I use a predefined exception (and which one) or should I create my own exception class, and should I extend it from some other exception class?
Thanks.

Is it a correct practice to throw an exception in that case?
Throwing an exception is a valid choice. Another valid choice would be to use some reasonable default value, and log a warning for the user explaining what has happened.
The choice depends on how sensitive is the value being configured. You have to make case-by-case decisions on this.
Should I use a predefined exception (and which one) or should I create my own exception class, and should I extend it from some other exception class?
If you choose to throw an exception in favor of a default value, throw a custom exception derived from Exception to make it "checked". This would ensure that there is code to handle the exception in the calling code.

1.) Yes
2.) Make your own one, named after the meaning of the value your loading.
You can simply extend IllegalArgumentException or NumberFormatException.
The more precise you are the better - makes your code and behaviour of your application clearer.
If the value you are talking of is of central/outstanding meaning for the application i would extend NumberFormatException with a more precice one. If there are more values than just this one that do not have distinguishable meaning you can also simply use NumberFormatException instead of extending it.

Related

How to enumerate all possible errors in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I don't mean every error in an individual program, I mean every error possible in Java 8. Is there somewhere in the Java Docs where you can find it?
It seems to me more of a research question rather than that of a solid implementation, but on any basis you have 2 lines of enquiry:
1) Any errors that can happen post compilation will only occur as instances of the Throwable type, if you want to track all of those down you'd need to include every single section of the runtime library (and any other possible user defined libraries included in your project) in a class that you intend to use to report them back to you or your running project program. You would then iterate over all of the currently defined classes using Reflection populating as you go a list with anything that returns true as instanceof Throwable - thats assuming you want all of the possible class names. The potential causes of those exceptions would only be hinted at by the documentation related to any given Throwable class.
2) On the other hand if you want all of the compile time-errors as well then you'll need to look in the source code for the Java compiler.
But in all honesty, the reason an exception is called an Exception is because it reports a fault based on an exceptional circumstance which you should be able to preempt during development. Anything faulty enough to stop a program working throws an exception and to catch anything Throwable without discerning the specific type is not something that should be considered for implementation - except perhaps if using a last chance saloon mentality (if my software hasnt resolved this over every condition I can forsee then it may be able to reset to base zero without falling over completely).
You can get a nice overview of these by looking at the package tree view of the java.lang package and navigate to Throwable (you can get to this view by selecting Tree in the navigation bar)
Throwable is the root of all errors and exceptions in Java. Notable Exceptions are
java.lang.Error: root of abnormal / fatal errors
java.lang.Exception: root of checked exceptions [*]
java.lang.RuntimeException: root of unchecked exceptions
[*] if extends Exception but not RuntimeException

How do you make changes in dynamic languages, and find all of the places that will be broken by that change? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am used to programming in static languages like Java, where changing the signature of a method will cause a compilation error for every line of code that calls the method I changed. This makes modifying large projects much more easy, because I can make a change, and then let the compiler tell me about all the places that I need to fix.
When dealing with a large project in a dynamic language like Python or Ruby, how do you make code changes, and still remain confident that you are not going to be surprised with a run-time error in production because of some scenario you forgot about?
I've seen my fair share of NullPointerExceptions and ArrayIndexOutOfBoundsExceptions in Java, so it's not like these things never happen in a static language, I would just think they happen a lot less.
Here are some ideas for providing some level of the protection that you are used to in Java:
As stated in a previous comment, you should definitely provide adequate unit and integration testing to prevent any issues during a refactor. Testing is even more important in a dynamic language than in a statically-typed language. You should check that values are properly passed and handled in each of your functions.
Use PyCharm and search for usages on a method prior to making the update. This is not full-proof, but does find a good amount of method usage to allow for an easier refactor.
Do a global find for the method name in your editor or search program of choice.
Provide exception handling in your functions for cases where the type is incorrect or a value is unset.
Handle args and kwargs passed into your function carefully. Perhaps provide an error or debug log if you receive an unexpected input.
Provide default values for undefined parameters to a function.
Here is an example of providing a default value for a parameter to ensure that it is defined and initialized to None (similar to null) in the function if it is not passed in with a value:
def my_function(my_parameter=None):
# Do something with my_parameter

Reusing an Exception class for a different purpose [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it in good practice to use an exception for a different purpose than the intended one, for the name? For example, I wanted an exception something along the lines of "Already exists" and I found the exception "EntityExistsException." The name was great, but it seems it was intended for the EntityManager. Is it okay to use the class, or should I create my own?
Read the documentation. Anyone unfamiliar with your code will look at the exception, and either know its documentation or go and read it.
In this case, the documentation says the exception is
thrown by the persistence provider when EntityManager.persist(Object)
is called
so if it is thrown in other circumstances by your code then your code isn't compatible with the Java API and has a bug.
I would tend to either use or subclass IllegalStateException for your case, since that is a general purpose exception, is widely used, and the state of 'the thing already existing' falls within its specification. If I expected that client code would handle the 'already exists' state differently than other failing states, then I would subclass it, otherwise I wouldn't.
This issue is probably best answered on a case by case basis, since "different purpose than the intended one" is a little bit vague to offer a complete suggestion on.
In your case, it may come down to a matter of taste. Personally, unless your already exists exception needs are related to the persistence layer, I would advise against reusing the exception from that package since it is easy to make a new exception and will not confuse any future developers or code that may infer the exception is being passed on from the underlying implementation.

Run-time vs. Compile-time in programming [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to know details about difference between run-time and compile-time. And what is run-time errors and compile-time errors? What are the differences between them?
Compile-time exceptions or errors are mistakes in your code that are obvious to the compiler that will create a broken program. Any IDE worth its salt will automatically mark these errors for you and won't even try to build.
Run-time exceptions are mistakes in your code that are not necessarily invalid code but when the program is run it leads to a state where things don't add up, illegal operations are attempted or some variable is null when something tries to use it. IDEs may or may not pick up on these mistakes and they are by far the harder type to track down. This is where getting used to using a debugger is incredibly important.
In summary:
compile-time: when trying to build/compile your code
run-time: when using already built code.
A run-time error is a type of error that occurs post compilation. Lets say you have a loop that iterates through an array. But your logic is a little off and you accidentally go out of bounds (IndexOutOfBoundsException), the compiler doesn't know that this is going to happen because it doesn't look for logical errors caused by the programmer or user in this way. NullPointerExceptions caused by null references are another runtime error. A compile-time error could be a syntax error; missing semi-colon for example.
You should read this article if you want to know about checked and unchecked exceptions, http://www.javapractices.com/topic/TopicAction.do?Id=129
It has an explanation of the difference between checked and unchecked exceptions which may help you understand the differences between the types of exceptions and the causes of them.
In terms of code invokation, most of it is done at compile time. When you instantiate an object, or call it's method. This is all compiled into instructions and are prepared at compile-time. However, if you want to invoke something during run-time, you can use what's called reflection to instantiate objects, or invoke methods at runtime.
http://www.programcreek.com/2013/09/java-reflection-tutorial/ this article may be useful about reflection.

Which type of exception should be generalized or created a base class for in a Java architecture [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
As a team lead which type of exception should I create a base class for in my architecture - checked or unchecked ? My team would start development in a few weeks and I want the architecture to be conducive to them for usage. Any reasons around that would also help.
That depends on the situation.
You use checked exceptions (extend Exception) for things that can go wrong regardless of the input the caller of the method passes. For example, network connections; you can make an HTTP GET request by calling client.get("google.com"); and everything goes well, two minutes later you call once again client.get("google.com"); and then you get an exception because of a network error. As you can see, here you called the same method passing the exact same input "google.com", yet you can get an exception at anytime. Therefore, you must force the caller to catch the exception by making it "checked", so that they handle those cases in which a network error occurs.
You use unchecked exceptions (extend RuntimeException) when the error happens because of some sort of invalid input by the caller of the method. For example, you have the method Integer.parse(String);. The method cannot work properly if you pass a null string here, so you throw an exception if that happens. This case, you should not force the caller to catch it, because the caller is responsible of passing the right input.
Overall: let the them decide, start with a short discussion. Helps people getting to know each-other.
I'd avoid checked exceptions: since they need to be explicitly catched, the catch block could become part of the normal program flow. Increases complexity and thus chance of introducing bugs.
Also don't use custom exceptions when possible, use existing exceptions like IllegalArgumentException. Avoid NullPointerExceptions by never returning null. Furthermore try to use something like bean-validation. That can save a lot of errors in your code caused by invalid (combinations of) arguments. And last but not least, failing fast is better then making your own faulty retry logic.

Categories

Resources