Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

But I don't _want_ to surround the statement with a try/catch block!

Tags:

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?

like image 863
Riley Lark Avatar asked Nov 02 '10 17:11

Riley Lark


People also ask

How do you surround try catch?

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.

How do you deal with a try catch block?

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.

What is the purpose of the catch block in a try catch statement?

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.

Should I put everything in a try catch?

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.


2 Answers

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);
 }
like image 126
Yishai Avatar answered Sep 18 '22 15:09

Yishai


There are two types of exception.

  • CheckedException: It make you force to use try-catch or throw to the top of program.
  • UncheckedException: You can bypass.. It would raise on runtime only

I just accept the fact that Java designed that way to make the program less error-prone.

like image 36
exiter2000 Avatar answered Sep 21 '22 15:09

exiter2000