黑马程序员技术交流社区
标题:
关于封装异常的问题,求大家帮忙解决一下
[打印本页]
作者:
yllw258
时间:
2012-6-18 17:10
标题:
关于封装异常的问题,求大家帮忙解决一下
为什么下边的程序总是提示非法语句开始了?请大家帮忙看看
class Demo
{
public static void func()
{
try
{
show();
System.out.println("A");
}
catch(Exception e)
{
System.out.println("B");
}
}
public static void main(String[] args)
{
try
{
func();
}
catch(Exception e)
{
System.out.println("C");
}
public static void show()throws Exception//将异常封装到方法中
{
throw new Exception();
}
System.out.println("D");
}
}
作者:
薄炳鑫
时间:
2012-6-18 17:17
你将下面这个方法写到main主函数中了,导致不能调用。
public static void show()throws Exception//将异常封装到方法中
{
throw new Exception();
}
将这个方法放到mian函数外面。
作者:
梁豹新
时间:
2012-6-18 17:27
函数之间是平级的,不能在函数中定义函数,你那个show()方法定认在main()内,函数之前只能调用。不能定义。
把show()方法定认在外面,在用主函数调用就行了。
作者:
胡大强
时间:
2012-6-18 17:33
class Demo1
{
public static void func()
{
try
{
show();
System.out.println("A");
}
catch(Exception e)
{
System.out.println("B");
}
}
public static void main(String[] args)
{
try
{
func();
}
catch(Exception e)
{
System.out.println("C");
}
}
public static void show()throws Exception { //将异常封装到方法中
{
throw new Exception();
//System.out.println("D");
}
// System.out.println("D");
}
}
我在你的基础上改了一下,,,
作者:
王晓新
时间:
2012-6-18 17:41
你的show()方法应该放到main方法外面来。
class Demo
{
public static void func()
{
try
{
show();
System.out.println("A");
}
catch(Exception e)
{
System.out.println("B");
}
}
public static void main(String[] args)
{
try
{
func();
}
catch(Exception e)
{
System.out.println("C");
}
System.out.println("D");
}
public static void show()throws Exception
{
throw new Exception();
}
}
复制代码
我运行了一下,输出是
B
D
这里我有一点疑问,为什么没有打印C,try{func()}中func()方法的try{show()}先抛出异常,接着执行catch进行处理,这里不打印A我理解。当func()执行完后不就是执行main()方法中的catch么?最后再打印D
作者:
李伟
时间:
2012-6-18 19:46
因为try{func()}没有接收到异常,所以就不用进行catch处理了,也就不用打印C了
作者:
陌花╮有意、
时间:
2012-6-18 20:20
楼主你的show()方法应该定义在类中而不是在main()函数内
作者:
黑马-王言龙
时间:
2012-6-18 21:05
内部方法,java暂不支持
将show()方法放到main()方法外就0k了
作者:
刘笑
时间:
2012-6-19 11:34
将show()方法放到main()方法外.本质:函数不能嵌套
作者:
张华廷
时间:
2012-6-19 12:03
public class diyitian {
/**
* @param args
*/
public static void show()throws Exception//将异常封装到类中
{
throw new Exception();
}
public static void func()
{
try
{
show();
System.out.println("A");
}
catch(Exception e)
{
System.out.println("B");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
func();
}
catch(Exception e)
{
System.out.println("C");
}
System.out.println("D");
}
}
作者:
yllw258
时间:
2012-6-19 13:31
王晓新 发表于 2012-6-18 17:41
你的show()方法应该放到main方法外面来。我运行了一下,输出是
B
D
我知道自己为什么错了,谢谢!
但是这样答案应该是BD,因为主函数中catch执行的前提是try抛出异常,而在主函数的try执行完之后没有抛出异常,所以不会输出C
作者:
yllw258
时间:
2012-6-19 13:33
标题:
RE: 关于封装异常的问题,求大家帮忙解决一下(已解决)
谢谢大家,我懂了!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2