Im confused how throw and catch work,I understand their are several mistakes with this ExceptionDemo. If someone could fix the mistake and clearly state why and how they corrected it without using all the Java jargon words, and use simple terms
Thank you
public class ExceptionDemo {
public static void main( String [] args ) {
try {
int number = Integer.parseInt(”123”);
if (number > 100) {
catch new ArithmeticException(”Check the number”);
}
}
catch {
System.out.println(”Cannot convert to int”);
}
finally (Exception e) {
System.out.println(”Always print”);
}
}
}
a bit tricky to tell exactly what is needed here. for starters looks like as would need to throw an exception if checking for some sort of valid value. also looks like the catch would need to have the exception handler itself not the finally.
//listing 1 slight re-work original post
public class Main {
public static void main(String[] args) throws ArithmeticException {
try {
int number = Integer.parseInt("123");
if (number > 100) {
// is this what trying to do?
//would expect typically would be used to handle
//something like div by zero, etc.
throw new ArithmeticException("Check the number");
}
}
//catch exception(s) here
catch (Exception e) {
System.out.println("Cannot convert to int:" + e.toString());
}
finally {
System.out.println("Always print");
}
}
}
//listing 2 more typical type thing maybe
public class Main {
public static void main(String[] args) {
try {
//int number = Integer.parseInt("A123"); // if un-comment throws generic exception bad input
int number = 100 / 0; //will throw an "arithmetic" exception
//
if (number > 100) {
//do something.
int x = number++;
}
}
catch (ArithmeticException arithEx){
System.out.println("An ArithmeticException Occurred:" + arithEx.toString());
}
catch (Exception e) {
System.out.println("A general exception occurred:" + e.toString());
}
finally {
//always gets executed. so is good place to clean up, close connections etc.
System.out.println("Always print");
}
}
}
In addition to hurricane's answer, you cannot catch a new exception. Instead you need to throw it.
throw new Exception();
Related
Consider this question I was asked in an interview
public class Test_finally {
private static int run(int input) {
int result = 0;
try {
result = 3 / input;
} catch (Exception e) {
System.out.println("UnsupportedOperationException");
throw new UnsupportedOperationException("first");
} finally {
System.out.println("finally input=" + input);
if (0 == input) {
System.out.println("ArithmeticException");
throw new ArithmeticException("second");
}
}
System.out.println("end of method");
return result * 2;
}
public static void main(String[] args) {
int output = Test_finally.run(0);
System.out.println(" output=" + output);
}
}
Output of this program throws ArithmeticException not UnsupportedOperationException
Interviewer simply asked how will i let the client know the original exception raised was of type UnsupportedOperationException not ArithmeticException.
I didn't know that
Never return or throw in a finally block. As an interviewer i would expect that answer.
A crappy interviewer looking for a minor technical detail might expect you know Exception.addSuppressed(). You can not actually read the thrown exception in a finally block so you need to store it in the throw block to reuse it.
So something like that:
private static int run(int input) throws Exception {
int result = 0;
Exception thrownException = null;
try {
result = 3 / input;
} catch (Exception e) {
System.out.println("UnsupportedOperationException");
thrownException = new UnsupportedOperationException("first");
throw thrownException;
} finally {
try {
System.out.println("finally input=" + input);
if (0 == input) {
System.out.println("ArithmeticException");
throw new ArithmeticException("second");
}
} catch (Exception e) {
// Depending on what the more important exception is,
// you could also suppress thrownException and always throw e
if (thrownException != null){
thrownException.addSuppressed(e);
} else {
throw e;
}
}
}
System.out.println("end of method");
return result * 2;
}
public class abc{
public static void main(){
try{
int a =10;
if(a=10){
throw new Exception();
}
l1:System.out.println(a);
}catch(Exception e){
continue l1;
}
}
}
Actually what I am trying to do is when an exception occurs I wish to continue the next statement after that as well.
Is there any way I can achieve it with Java?
You would just want to put System.out.println(a); in the catch block.
Putting it in a finally block would mean that it is executed even when an exception does not occur. The program only goes to the catch block when an exception occurs.
I think this is what you want?
public static void main(String[] args) {
int a = 9;
try {
if (a == 10) {
throw new Exception();
}
} catch (Exception e) {
e.printStackTrace(); // only if there is any exception
} finally {
System.out.println(a); // always print this message
}
}
Or if a is 10
public static void main(String[] args) {
int a = 10;
try {
if (a == 10) {
throw new Exception();
}
} catch (Exception e) {
e.printStackTrace(); // only if there is any exception
} finally {
System.out.println(a); // always print this message
}
}
try some thing like
int a =0;
try{
a =10;
if(a=10){
throw new Exception();
}
} catch(Exception ex){
//do nothing
} finally {
l1:System.out.println(a);
}
Anyway in java avoid jumping
The method processExceptions() should call the method BEAN.methodThrowExceptions and handle exceptions:
1.1. if an exception FileSystemException occurs, then log it by calling the method BEAN.log and throw forward
1.2. if an exception CharConversionException or any other IOException occurs, just log it by calling the method BEAN.log
Add the class/type of the exception you are forwarding in 2.1. to the processExceptions() method signature.
Handle the remaining exception in the method main() and log it. Use try..catch
I tried different solutions. It works but not as it should. What is the correct placement of throws in methods. Or maybe i shouldnt use them at all? And if I don't place them I can't make use of throw. Please help, I would really appreciate your time.
public class Solution {
public static StatelessBean BEAN = new StatelessBean();
public static void main(String[] args) {
try{
processExceptions();
}
catch (CharConversionException e){
BEAN.log(e);
}
}
public static void processExceptions()throws CharConversionException {
try{
BEAN.methodThrowExceptions();
}
catch (CharConversionException e){
BEAN.log(e);
throw e;
}
catch (FileSystemException e){
BEAN.log(e);
}
catch (IOException e){
BEAN.log(e);
}
}
public static class StatelessBean {
public void log(Exception exception) {
System.out.println(exception.getMessage() + ", " + exception.getClass().getSimpleName());
}
public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException {
int i = (int) (Math.random() * 3);
if (i == 0)
throw new CharConversionException();
if (i == 1)
throw new FileSystemException("");
if (i == 2)
throw new IOException();
}
}
}
If a method is capable of throwing an exception which IS NOT RuntimeException (either directly throwing or invoking a method which can throw an exception), it should either handle the exception or declare that it throws the exception, so that any other method which calls this method would know that it can encounter an exception and can either handle it or declare it that it throws (and so on).
Since you are dealing with checked exception, there is no clean way to avoid declaring throws, but there is a (messy) workaround. You can wrap the exception in a RuntimeException and can throw it and when you want to handle it, you can get the actual exception from the re.getCause();
public class Solution {
public static StatelessBean BEAN = new StatelessBean();
public static void main(String[] args) {
try{
processExceptions();
}
catch (RuntimeException re){
if (!(re.getCause() instanceof CharConversationException)) {
//handle the case in which the exception was not CCE and not FSE not IOException
}
}
}
public static void processExceptions() {
try{
BEAN.methodThrowExceptions();
} catch (CharConversionException cce){
BEAN.log(e);
throw new RuntimeException(cce);
} catch (FileSystemException fse){
BEAN.log(e);
} catch (IOException e){
BEAN.log(e);
}
}
public static class StatelessBean {
public void log(Exception exception) {
System.out.println(exception.getMessage() + ", " + exception.getClass().getSimpleName());
}
public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException {
int i = (int) (Math.random() * 3);
if (i == 0)
throw new CharConversionException();
if (i == 1)
throw new FileSystemException("");
if (i == 2)
throw new IOException();
}
}
}
I am not sure whether I understood your question correctly and this is what you wanted :)
I think that the order:
Handle the remaining exception in the method main()
means that you should catch not only CharConversionException, but all other Exceptions by:
catch (Exception e)
Besides, you should ask it on help.javarush.net I think :>
I am writing a small calculator that goes through the input in token form by using streamtokenizer. However, when catching an exception I want it to either ignore all other exceptions, or move to the EOL. I can't just break as the progream isn't meant to crash, just ignore all succeeding exceptions for that input.
So either I try to set up exceptions to ignore every exception following the first, or I try to get streamtokenizer to move to EOL after catching an exception.
Either way I have no idea to get any of the two options functional.
public static void main(String[] args) throws customException {
Calculator casio = new Calculator(new Stokenizer());
while (true) {
try {
casio.statement();
}
} catch (customException error) {
System.out.println(syntaxError.getMessage());
}
}
}
Stream tokenizer docs is found at http://docs.oracle.com/javase/7/docs/api/java/io/StreamTokenizer.html
You could try something like that to go to the end of line:
public void statement() throws IOException {
int tt = StreamTokenizer.TT_EOF;
try {
while((tt = tokenizer.nextToken()) != StreamTokenizer.TT_EOF) {
// ...
}
} catch (CustomException syntaxError) {
System.out.println(syntaxError.getMessage());
gotoEOL();
}
}
private void gotoEOL() {
try {
while(tokenizer.nextToken() != StreamTokenizer.TT_EOL)
;
} catch (IOException e) {
e.printStackTrace();
}
}
Using A4Ls answer I made a little function and added it before every throw. Probably not the best solution, but it works.
private void gotoEOL() {
while (!tokenizer.isEOL()) {
tokenizer.nextToken();
// System.out.println(tokenizer.getToken());
}
I'm trying to fix an issue, in my application I have this code
try {
object1.method1();
} catch(Exception ex) {
JOptionPane.showMessageDialog(nulll, "Error: "+ex.getMessage());
}
and the object1 would do something like that:
public void method1() {
//some code...
throw new RuntimeException("Cannot move file");
}
I get a messsage in my option pane like this:
Error: java.lang.RuntimeException: Cannot move file
but I used getMessage and not toString method, so the name of the class shouldn´t appear, right?
What I am doing wrong?
I already tryied with a lot of exceptions, even Exception itself. I'm looking to solve this no without the need to implement my own Exception subclass
PROBLEM SOLVED - thank you all!
The try and catch were actually being called in get() method from SwingWorker which constructs an ExecutionException with my exception thrown from doInBackground()
I fixed doing this:
#Override
protected void done() {
try {
Object u = (Object) get();
//do whatever u want
} catch(ExecutionException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getCause().getMessage());
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message