throw:
throw is used in re-throwing exception process or we can say that it is used to throw an exception object explicitly. It can take at most one argument which will be an exception object. Only unchecked exception can be thrown.
Syntax:
throw exceptionObject;
Example
public class Main { public int reminderTest(int number1, int number2) { try{ return number1/number2; }catch(ArithmeticException e){ throw e; } } public static void main(String[] args) { Main main = new Main(); try{ System.out.println(main.reminderTest(40, 0)); }catch(Exception e){ e.printStackTrace(); } } } |
Output
java.lang.ArithmeticException: / by zero at Main.reminderTest(Main.java:5) at Main.main(Main.java:14) |
throws:
throws keyword is used to throw an exception object implicitly. The throws keyword is used with the method signature. We can declare more than one type of exceptions with method signature which should be comma separated.
Note:
1.    throws is commonly used to throw checked exception.
2.    If we are calling a method that declares an exception then we must have to either caught or declare the exception.
3.    Exception can be re-thrown.
Syntax:
methodName () throws comma separated list of exceptionClassNames{}
Example
public class Main { public int reminderTest(int number1, int number2) throws ArithmeticException, Exception{ return number1/number2; } public static void main(String[] args) { Main main = new Main(); try{ System.out.println(main.reminderTest(40, 0)); }catch(Exception e){ e.printStackTrace(); } } } |
Output
java.lang.ArithmeticException: / by zero at Main.reminderTest(Main.java:4) at Main.main(Main.java:10) |
Difference between throw and throws.
                    throw keyword |                     throws keyword |
|
|
Java interview questions on Exception Handling
- what is an exception?
- How the exceptions are handled in java?
- What is the difference between error and exception in java?
- Can we keep other statements in between try catch and finally blocks?
- Explain the exception hierarchy in java?
- What are runtime exceptions in java?
- What is outofmemoryerror in java?
- What are checked and unchecked exceptions in java?
- What is the difference between classnotfoundexception and noclassdeffounderror in java?
- Will finally block get executed if return?
- Can we throw an exception without throws?
- What is rethrowing an exception in java?
- What is the use of throws keyword in java?
- What is exception propagation in java?
- Difference between throw and throws in java?
- What is finally in java?
- What is the difference between final finally and finalize in java?
- How to create customized exceptions in java?
- What is classcastexception in java?
- What is stackoverflowerror in java?
- What is the superclass of all exception classes?
- What is the use of printstacktrace method in java?
- What is arraystoreexception in java?