• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception as a argument

 
naveen yadav
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ranchers
i am quite suprised at the follwing code



when new Exception() is encountered which is a throw point a normal execution of program should be disrupted.
But the above code works fine , loop executed 10 times as in normal case.

I could understand that it is a just a exception is an object which can be passed to a method just like any other object.
But still at run time exception should have been encountered on line 3.






 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's created a new Exception at line 3. But it hasn't been thrown. There's no throw new Exception... statement. And unless an Exception is thrown it's just like any other object.

It would be very unusual to use it like this. But a common occurrence would be to catch an exception and then pass it into a method (e.g. a logging method) - that's not really all that different to what's happening here.

Note that since it's an Exception, not a RuntimeException, if it was being thrown the compiler would force you to handle or declare it.
 
naveen yadav
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:
It's created a new Exception at line 3. But it hasn't been thrown.


yes , i misunderstood new Exception().


i have one more doubt that Are both checked and unchecked are checked by compiler at compile time ?


 
ayush raj
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are both checked and unchecked are checked by compiler at compile time ?


Only checked exceptions are checked by the compiler during compile time . The unchecked exceptions are not checked by the compiler . So , this is also a classification of exceptions : 1>checked
2>unchecked exceptions
 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Thrower {
public static void main(String[] args) throws Exception {
sneakyThrow(new Exception("This is a checked exception"));
throw new Exception();
}

public static void sneakyThrow(Throwable t) {

for(int i=0; i<10; i++)
System.out.println("get"+t);
}
}


If you change this code like the above, the main method does throw the checked exception at run time. You can declare a Runtime exception too.
In order to have the method throw an exception, put "throw new XXException()" in a line, and declare it in the method. This will make the method throw the exception.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic