Exception in thread “main” java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results. The solution: For console apps, use a single Scanner to read from System.in. Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine(). See: Do not create multiple buffered wrappers on … Read more

What is the proper way to handle a NumberFormatException when it is expected?

Is there a method that I can call that will tell me if Integer.parseInt() will throw a NumberFormatException before calling it? Then I would have no problem logging this, since it should never happen. Sadly, no. At least not in the core Java API. It’s easy to write one, however – just modify the code … Read more

How can I safely create a nested directory in Python?

On Python ≥ 3.5, use pathlib.Path.mkdir: For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try os.path.exists, and consider os.makedirs for the creation. As noted in comments and elsewhere, there’s a race condition – if the directory is created … Read more

What is a StackOverflowError?

Parameters and local variables are allocated on the stack (with reference types, the object lives on the heap and a variable in the stack references that object on the heap). The stack typically lives at the upper end of your address space and as it is used up it heads towards the bottom of the address space (i.e. towards zero). Your process also … Read more

Manually raising (throwing) an exception in Python

How do I manually throw/raise an exception in Python? Use the most specific Exception constructor that semantically fits your issue. Be specific in your message, e.g.: Don’t raise generic exceptions Avoid raising a generic Exception. To catch it, you’ll have to catch all other more specific exceptions that subclass it. Problem 1: Hiding bugs For example: … Read more