Pro/Cons of exceptions over the errorString() method [closed] - java

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 9 years ago.
Improve this question
I normally code in C++ using Qt framework. And for error handling I use the standard that Qt uses, which is calling a function like errorString() when a function behaves unexpectedly. For the current project I'm working on, I need to write my code in Java, and it is common to use Exceptions with try-catch-finally mechanism in Java.
My question is, will it be a big mistake to use errorString() like approach for error handling in Java. What are the advantages and disadvantages of using exceptions other than errorString().
Thank you.

The advantages are (according to Oracle's Advantages of Exceptions article):
Separating error-handling code from "regular" code
Propagating errors up the call stack
Grouping and differentiating error types
It is generally a good idea to write idiomatic code, sticking to the conventions and practices of the language you develop in. As I see it, that's an advantage in itself.
As far as cons go, at the top of my head:
It's really annoying to lazy programmers because you have to surround your code in try/catch, this may make it slightly more difficult to ignore the exceptions (I see this as an advantage).
It's easily misused by programmers who are new to the concept, and in turn you get severely uglified codebase on top of an arcane home-brewed error reporting system.
As far as whether or not it will be a mistake goes, well, as long as the entire team are Qt masterminds and have to write something in Java on an accidental basis and this code will never have to be managed by anyone who is supposed to be a Java expert, then sure - make a familiar environment for yourself and your team. But in any other circumstance, I highly recommend that you use exceptions instead.

The advantage is solely dependent on your implementation... See, for instance, you can catch a particular exception, wrap it and throw its parent exception ( a mechanism which is very widely used..). This way you can have a hierarchy of exceptions and you handle all exceptions in a general way... Suppose you have a DB and assume for some reason you get a connection exception... Now, you dont have to worry about handling that exception there and then.. you say that your method "throws" this exception and let the caller worry about it..the caller might wait for some time and then try to connect to DB again,,, Furthermore you can use finally to release resources/clean up... You are doing much more than errorString() (printing an error message..) . You can also include logging in here if you want to..

Related

Advice for how Java classes should be organized [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 3 years ago.
Improve this question
I'm fairly new to Java but love it so far. My question is, i'm a little unfamiliar with Classes. I know what they are, and generally how to work with them as I'm not brand new to programming, but I would like a professionals opinion.
I'm currently writing a small multi threading program to launch parallel power shell sessions by spawning cmdlines for target machines in a csv, capture the output and write to a csv.
Should I put everything into one class and breakup the logical operations to methods within the class and string them together? Or should I make a Thread executor class, cmdline powershell class, a csv operations class, etc (My thought behind that was to allow code reuse, but that'll be kindove time consuming and in my mind impractical since i'd have to specify the datatypes and return types for new situations in the future).
Any help would be appreciated!
There is no "way" so to speak,
It's all your preference.
But just don't cram everything into one class.
Generally, you want to be as neat as possible.
In the future, you will thank yourself for using different classes.
If your project grows, and a bug is born, you don't want to be looking through one very long class, but instead simple broken up pieces.
Let's say you have these classes:
GPS,
Main,
Search
And someone reports a bug with the GPS not working.
Instead of looking everywhere saying, where did I put the GPS code,
it's right in front of your eyes!
I've went to everyones links and found the info very helpful. So far I've come up with this.
Make a package that contains classes that perform a specific set of tasks (also don't make utility kits that are very general). The package in my case would be called com.jt.threads.powershell or something.
Keep classes small and breakup the program by conceptual types. (ie. data reading and writing operations on a filesystem should be in one class with the focus on helping the package perform a certain task or range of tasks.)
Methods within classes should focus on getting, setting, changing the objects attributes or adding logic.
The program entry point should join it all together, except in the case of large applications, in which case an interface should be used (still learning about them).
With true OOP, i don't think it's a good idea to create code for reuse, unless it's supporting a range of very very very similar tasks (that way if I have to change something, it won't break other classes outside of the package).
Thank you all! I feel a lot better knowing that I'm on the right track. I was worried that by NOT making code reusable in a lot of situations that I was doing something wrong. I started programming in Python 6 months ago for my job, but I totally ignored classes and I want to have good programming habits and apply OOP as best I can going forward! Python is definitely convenient and a great starter language, but I wish I learnt Java first so I can get a solid grasp on OOP.
There is no “The way” to organize or group classes. Anything goes as long as it works as expected and you understand what you write.
As a Programmer you only need to,
1. Know and understand what you write.
2. Know and understand what other Programmer as written.

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