简体   繁体   中英

Bypass a Java error

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 ?

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
}

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(iedeclare 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM