Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
2.00/5 (4 votes)
See more:
Hi .
I am new in java, i am wondering about the difference between using and
Java
throw and throws and try catch and finally
when i use all of these exception handlers and what are the run time exceptions and checked exceptions
Posted
Updated 28-Nov-11 23:53pm
v4

See here[^] for a good introduction on exception handling.
 
Share this answer
 
There are 2 ways to deal with exceptions:

you can throw an exception:

Java
public int foo() throws Exception{
  // fancy code that needs Exception handling 
  // like reading a file or parsing a int value
}


here you pass back the exception instead of the desired int-value. the method above has to deal with the exception and probably to pass it on or to deal with it.

Other version is to catch the exception direct:

Java
public int foo() throws Exception{
  try{
    // fancy code that needs Exception handling 
    // like reading a file or parsing a int value
  }
  catch(Exception oException){
    oException.printStackTrace();
    return -1;
  }
}


in this case you catch the exception and often return a invalid int-value like -1. You can add a finally { } behind the catch to make sure certain operations are carried out no matter if the try/catch fails or not (e.g. closing file streams, making sure the database does not become invalid).
 
Share this answer
 
v2
You are asking for info you may easily find yourself on the web: Google results for "Java exception handling tutorial"[^]
 
Share this answer
 
Comments
elgaabeb 29-Nov-11 6:12am    
This is the way to fish :). 5'd.
CPallini 29-Nov-11 6:20am    
Thank you. :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900