#29 - Exception Handling Throw & Throws Keyword Part3
Throw keyword: In Java exception handling, we use throw keyword to throw a single exception explicitly. It is followed by an instance variable. Using throw keyword, we can throw either checked or unchecked exception in Java. The keyword throw raises an exception by creating a subclass object of Exception explicitly. We mainly use throw keyword to throw custom exception on the basis of some specified condition. We use keyword throw inside the body of method or constructor to invoke an exception. With the help of throw keyword, we cannot throw more than one exception at a time What is throws in Java? The throws keyword is used in a method declaration to indicate that the method might not handle an exception itself and instead passes the responsibility to the caller method. It acts as a warning signal to the programmer: “This method may generate an exception. Handle it where you call it.” Why do we use throws? We use throws because: Some exceptions cannot or should not be handled immediately Syntax of throws Difference between Throw and Throws in Java The keyword throw is used to throw an exception explicitly, while the throws clause is used to declare an exception. Throw is followed by an instance variable, while throws is followed by the name of exception class. We use throw keyword inside method body to call an exception, while the throws clause is used in method signature. With throw keyword, we cannot throw more than one exception at a time, while we can declare multiple exceptions with throws.
