public class SearchForExceptionHandler
{
public static void main(String[] args)
{
try
{
System.out.println("Method main called");
methodA();
}
catch(MyException e)
{
System.out.println("Exception caught in Main");
}
}
static void methodA()
{
System.out.println("Method A called");
methodB();
}
static void methodB()
{
System.out.println("Method B called");
methodC();
}
static void methodC()
{
System.out.println("Method C called");
new MyException();
}
}
class MyException extends Throwable
{
public MyException()
{
System.out.println("Exception thrown in MyException");
}
}编译时出现下面的问题
E:\Java\JavaLab\Chapter12\SearchForExceptionHandler.java:16: exception MyException is never thrown in body of corresponding try statement
catch(MyException e)
^
1 error不知道什么原因? 请教
{
public static void main(String[] args)
{
try
{
System.out.println("Method main called");
methodA();
}
catch(MyException e)
{
System.out.println("Exception caught in Main");
}
}
static void methodA()
{
System.out.println("Method A called");
methodB();
}
static void methodB()
{
System.out.println("Method B called");
methodC();
}
static void methodC()
{
System.out.println("Method C called");
new MyException();
}
}
class MyException extends Throwable
{
public MyException()
{
System.out.println("Exception thrown in MyException");
}
}编译时出现下面的问题
E:\Java\JavaLab\Chapter12\SearchForExceptionHandler.java:16: exception MyException is never thrown in body of corresponding try statement
catch(MyException e)
^
1 error不知道什么原因? 请教
{
System.out.println("Method main called");
methodA();
}
这段代码中没有异常会抛出,所以不需要用try
{
public static void main(String[] args)
{
try
{
System.out.println("Method main called");
methodA();
}
catch(MyException e)
{
System.out.println("Exception caught in Main");
}
}
static void methodA() throws MyException
{
System.out.println("Method A called");
methodB();
}
static void methodB() throws MyException
{
System.out.println("Method B called");
methodC();
}
static void methodC() throws MyException
{
System.out.println("Method C called");
throw new MyException();
}
}
class MyException extends Throwable
{
public MyException()
{
System.out.println("Exception thrown in MyException");
}
}
Method A called
Method B called
Method C called
Exception thrown in MyException
Exception caught in Main