• Post Reply Bookmark Topic Watch Topic
  • New Topic

what happens if we dont use a throws exception to a method?  RSS feed

 
senthil sen
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what happens if we dont use a throws exception to a method?will the jre catch the exception automically?
 
Leandro Oliveira
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it depends!!!
if u are writing a method that implicitly or explicitly throws any checked exception u must catch it, so when u try to compile this code the compiler refuse to compile, the checked exception (the ones like InterruptedException, or IOException) must be catched in a try/catch block.
for example:

public class test{
publi static void main(String args[]){
Thread.sleep(200);
}
}
 
Leandro Oliveira
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it depends!!!
if u are writing a method that implicitly or explicitly throws any checked exception u must catch it, so when u try to compile this code the compiler refuse to compile, the checked exception (the ones like InterruptedException, or IOException) must be catched in a try/catch block.
for example:

public class test{
publi static void main(String args[]){
Thread.sleep(200);
/*this wont compile, there must be a try/catch block*/
}
}
to solve u have two options:
place the Thread.sleep(200) inside a try/catch or make the main method subject of throwing an exception:
public static void main(String[] args) throws Exception{
//code
}
if there isn't any catch to handle the exception, the current Thread will end, and there will be a message in the standard output!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!