I'm writing a program that uses java.net.URLDecoder.decode(String value, String encoding)
. Apparently, this method might throw an UnsupportedEncodingException
, which I get. But I'm just passing "UTF-8" as the encoding. It won't throw that exception.
I could just surround the darn thing with a catch block that does nothing, but then in whatever freak case does cause the exception to be thrown, I won't find out about it. I do not want to create a big chain of throws UnsupportedEncodingException
up to the top of my program, either.
What can I do here? Why am I forced to deal with some Exceptions, while others (e.g. IllegalArgumentException
, NullPointerException
) I'm allowed to ignore?
In Eclipse, just surround the code you want to enclose with the try-catch block and right-click, then select **Surround with > Try Catch **block. Although you can only have one try statement per try-catch block, you can have multiple catch blocks.
Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.
Try/catch blocks allow a program to handle an exception gracefully in the way the programmer wants them to. For example, try/catch blocks will let a program print an error message (rather than simply crash) if it can't find an input file. Try blocks are the first part of try/catch blocks.
You should not catch any exceptions that you can't handle, because that will just obfuscate errors that may (or rather, will) bite you later on. Show activity on this post. I would recommend against this practice. Putting code into try-catch blocks when you know the types of exceptions that can be thrown is one thing.
I think you need a better grasp of checked exceptions and their purpose in general, but that is for another question and answer. In this case what you do is:
try {
//etc.
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
There are two types of exception.
I just accept the fact that Java designed that way to make the program less error-prone.
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