0

Is there a way that I can bypass an error message in Java ? What if I get an error, but there is no viable way to change my program ? What if I suspect that I might get an error from a block of code, but I don't know when or if it will happen ? There's been a lot of times where I had to let something be in my code, but produced an error. For example, converting a string into a float with parseFloat().

Anyway to do this ?

Soutzikevich
  • 963
  • 3
  • 13
  • 29
  • As the answers suggest _Exception handling work_ . But nothing can be done when _there is no viable way to change my program ?_ – Suraj Rao Jun 05 '17 at 06:35

3 Answers3

2

I think you need a try...catch statement.

try {
    // parse your float here
} catch (NumberFormatException ex) { // parsing a float might throw a NumberFormatException
    // code in here will be executed if a NumberFormatException occurs
}
Graham
  • 7,035
  • 17
  • 57
  • 82
Sweeper
  • 176,635
  • 17
  • 154
  • 256
2

Yes you can handle runtime errors in Java.

Exception Handling

There are two ways to handle Exceptions.

  1. Throw out and ignore -

When an Exception occur inside a code of program simply throw it out and ignore that an exception occur(i.e.declare the methods as throws Exception).

Example:

void method()throws IOException{  

 }  
  1. Catch and handle -

If a code snippet is generating an Exception place it inside a try block. Then mention the way to handle the Exception inside the catch block.

Example for catch and handle:

try{
  double a= parseDouble("12.4a");
}catch(NumberFormatException e){
  System.out.println("cannot format");
}

Here try to convert 12.4a to double and store in a. Since 12.4a contains character a NumberFormatException will occur. you can handle it. In above code I just print a text. But you get printStackTrace:

e.printStackTrace;

You can add finally after catch block. read Orcale doc.

Blasanka
  • 18,202
  • 10
  • 89
  • 96
1

Yes, of course there is a way to do this, it is called Exception Handling.

Begin by reading about the Exception class, and the try catch and finally keywords.

Here is a starting point: https://www.tutorialspoint.com/java/java_exceptions.htm

Mike Nakis
  • 50,434
  • 8
  • 92
  • 124
  • 1
    Hey Mike, I just noticed that I never gave you an upvote for helping me when I was a complete newbie, and so I apologise about that :) Here you go! – Soutzikevich Jul 06 '21 at 18:13