日期:2014-05-20  浏览次数:20738 次

java 异常代码求解
/不能正常抛异常抛异常,编译。运行都没事,找不出问题很痛苦,求助大神

public class ThrowTest 
{
public static void main(String[] args) 
{
try
{
throwChecked(-3);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
throwRuntime(-3);
System.out.println();
}
public static void throwChecked(int a)throws Exception 
{
if(a>0)
{
throw new Exception("a的值大于0.不符合要求");
}
}
public static void throwRuntime(int a)
{
if(a>0)
{
throw new RuntimeException("a的值大于0.不符合要求");
}}
}


------解决方案--------------------
按照你方法里的内容,要填正数才能抛异常
你-3当然不抛了
------解决方案--------------------
public class ThrowTest
{
public static void main(String[] args)
{
try
{
throwChecked(-3);  //第一步:调用throwChecked(-3)方法;

catch (Exception e)
{
System.out.println(e.getMessage());
}
throwRuntime(-3);
System.out.println();
}

public static void throwChecked(int a) throws Exception
{
if (a > 0)      //第二步,因为参数a <0 不符合要求;
{
throw new Exception("a的值大于0.不符合要求");
}
}

public static void throwRuntime(int a)
{
if (a > 0)        //第二步,因为参数a <0 不符合要求;
{
throw new RuntimeException("a的值大于0.不符合要求");
}
}
}

你的方法写对了没?
仔细检查下哦;
------解决方案--------------------
你想自定义异常,应该继承Exception这个抽象类。例如:
public class DAOException extends Exception {
public DAOException(
String message, Throwable cause) {
super(message, cause);
}
}

try {  可能出错的地方

} catch (DAOException e) {
e.printStackTrace();
}

你写的只是两个方法,然后调用这两个方法,与异常无关。好好研究一下异常。