Recently, I had interview with company and they gave me a coding problem. I was given program related to deck of cards and one of the methods was to shuffle the deck of cards. So I wrote the program as:
/** Shuffle the list of cards so that they are in random order * @param d Deck of cards*/ public static void shuffle(Deck d) { if(d == null) throw new IllegalArgumentException(); Random randomGenerator = new Random(); List<Card> cards = d.getDeckOfCards(); // cards is basically Linked List.. cards = new LinkedList<Cards>() for(int i=0;i<cards.size();i++) { int randomNumber = randomGenerator.nextInt(52); Card c1 = cards.remove(randomNumber); Card c2 = cards.remove(0); cards.add(0, c1); cards.add(randomNumber,c2); } }
In the above code, I have thrown IllegalArgumentException which I'm most doubtful about. Under what conditions should actually throw a runtime exception? Should we actually throw runtime exception?
Thanks
One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null . If an argument is null , the method might throw a NullPointerException , which is an unchecked exception.
Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them. Catching Throwable will catch everything. This includes all errors, which aren't actually meant to be caught in any way.
The custom exception should extends RuntimeException if you want to make it unchecked else extend it with Exception . With unchecked exceptions calling code method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.
Runtime Exceptions are also used when a condition that can't happen. It should be noted that when a program is running out of memory, a program error is thrown instead of showing it as a Runtime Exception.
Should we actually throw runtime exception?
Yes, we should. Runtime exception serve a specific purpose - they signal programming problems that can be fixed only by changing code, as opposed to changing the environment in which the program runs.
Under what conditions should actually throw a runtime exception?
When you detect an error with the way your class or method is used, throw a runtime exception.
Generally, there are two categories of situations when you need to throw a runtime exception:
In this sense, your code is fine: it fits squarely in the first category, i.e. passing invalid parameter values. One thing I would do slightly differently is adding a message to say which parameter had an invalid value, but in your case it is not critical, because there is only one parameter there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With