santosh pilla wrote:1)In the above code when s2() function is being called within s1 .then s2 function is like this void s2() throws Exception but here within s2() function we are not throwing any thing ...like throw new Exception ..so why doesn't the compiler sees it and consider it as a mistake !
Why should the compiler consider it as a mistake. If you are thinking how try and catch blocks work, it is not the case with the keyword
"throws"
In case of try if you are not throwing a Checked Exception, the compiler gives an error. But, if throws declares a Checked Exception, it doesn't bother to see if the exception is really thrown.
And in this case the code could actually throw an exception. It is calling s3 which throws an exception, so it either has to handle it or declare.
santosh pilla wrote:2) and s2() function throws Exception like void s2() throws Exception then the function which calls it (s1) should either handle the exception or it may pass the excepion but here it is handling it ..but s2() function doesnt have any keyword like throw ......
You are in
java, please call it a
method rather than a
function.
s2() method doesn't have a throw keyword, but it has a call to s3 which could throw an exception
santosh pilla wrote:3)void s2() throws Exception means --- Exception class is a super class of all Exceptions (checked and unchecked ) then when we say throws Exception then is it throwing checked Exception or unchecked Exception ...
It means both. But the compiler worrys only about the Checked Exception
Suppose a method1() throws RuntimeException. You have another method2() calling method1(). Then method2() doesn't need to handle or declare it.
Suppose a method1() throws Exception. You have another method2() calling method1(). Then method2()
does need to handle or declare it.
santosh pilla wrote:4) can we have try and catch block in void s3() function as
void s3() throws Exception
{
try
{}
No.You haven't caught any exceptions. And try catch need you to actually throw a checked Exception