Throw和Throws的区别和运用

Throw是自行抛出错误,并生成指定的异常对象.大家可以看下下面的代码:
    public static void main(String[] args) {
        
// TODO 自动生成方法存根

        
try
        
{
            
double d =90/0.0;
            System.
out.println("浮点数除以0"+d);
            
if(String.valueOf(d).equals("Infintiy"))
                
throw new ArithmeticException("除0异常");
        }

        
catch(ArithmeticException e)
        
{
            System.
out.println(e);
        }

        
    }

Throws:如果方法出现错误,但是无法处理异常,可以在方法声明处用Throws子句来声明抛出的异常.
    public static void main(String[] args) throws IOException{
        
// TODO 自动生成方法存根

        BufferedReader buf;
        String str;
        
while(true)
        
{
            buf 
=new BufferedReader(new InputStreamReader(System.in));
            System.
out.print("请输入数字");
            str 
=buf.readLine();
            
try
            
{
                Integer.valueOf(str);
                System.
out.println("转型成功");
            }

            
catch(Exception e)
            
{
                System.
out.println("转型失败!");
            }

        }

    }
posted @ 2008-04-21 22:35  啊文  阅读(438)  评论(0编辑  收藏  举报