MOCKSTACKS
EN
Questions And Answers

More Tutorials









Java Throw vs Throws


The Throw Keyword:


The throw keyword is used to throw an exception explicitly by the programmer

    if ( b===0 ) {
       throw new ArithmeticException("Div by 0");
          }
     else{
             return a/b ;
         }

In a similar manner, we can throw user defined exceptions:

 throw new My Exception ( "Exception throw" );

The throw Keyword


Throws java throws keyword is used to declare an exception.

This gives an information to the programmer that there might be an exception so its better to be prepared with a try catch block!

    public void calculate (int a, int b) throws IOException {

            // code

    }


package com.company;

class NegativeRadiusException extends Exception{
    @Override
    public String toString() {
        return "Radius cannot be negative!";
    }

    @Override
    public String getMessage() {
        return "Radius cannot be negative!";
    }
}

public class throw_throws {

    public static double area(int r) throws NegativeRadiusException{
        if (r<0){
            throw new NegativeRadiusException();
        }
        double result = Math.PI * r * r;
        return result;
    }

    public static int divide(int a, int b) throws ArithmeticException{
        // Made By Harry
        int result = a/b;
        return result;
    }
    public static void main(String[] args) {
        // Shivam - uses divide function created by Harry
        try{
//            int c = divide(6, 0);
//            System.out.println(c);
            double ar = area(6);
            System.out.println(ar);
        }
        catch(Exception e){
            System.out.println("Exception");
        }
    }
}


Conclusion

In this page (written and validated by ) you learned about Java Throw vs Throws . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java Finally Block.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.