Yes you can handle runtime errors in Java.
Exception Handling
There are two ways to handle Exceptions.
- 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{
}
- 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.