Java - Difference between throw and throws in Exception handling

http://javarevisited.blogspot.de/2012/02/difference-between-throw-and-throws-in.html

Sometimes I can't open this page without proper proxy configuration, so I have to copy the content here.


Main difference between throw and throws is in their usage and functionality. where throws is used in method signature to declare Exception possibly thrown by any method, throw is actually used to throw Exception in Java code.

Here is an example of both throw and throws keyword which makes it easy to understand difference between them.

public void shutdown() throws IOException{
        throw new IOException("Unable to shutdown");
}

1)  You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException("not able to open connection").

2)  throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception.

throw keyword can also be used in place of return as shown in below example:

private static boolean shutdown() {
        throw new UnsupportedOperationException("Not yet implemented");
}

3)  throws keyword cannot be used anywhere except method signature while throw keyword can be used inside method or static initializer block as shown in example.

static{
        try {
            throw new Exception("Not able to initialized");
        } catch (Exception ex) {
            Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
        }
}

4) throw keyword can also be used to break a switch statement without using break keyword as shown in below example:

int number = 5;
switch(number){
            case 1:
                throw new RuntimeException("Exception number 1");
            case 2:
                throw new RuntimeException("Exception number 2");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值