Use of throw and throws keyword

Throw Keyword

Throw keyword is used to fire the exception manually. If an unexpected or unwanted situation occurs within a program block, it is better to notify the application. This can be done by throwing an exception from the code. You can throw one of many java exceptions or can create a custom exception which should be subclass of one of the java exceptions. One can throw multiple exceptions from try-catch block.


public class NegativeIntegerException extends RuntimeException {
	public NegativeIntegerException(final String message) {
		super(message);
	}
}

public class TestC {
	public boolean negativeTest(final int i) throws MyCustomException {
	  if(i < 0) {
	    throw new NegativeIntegerException("Number is negative");
	  }
	  return true;
	} 	
}

Throws Keyword

Throws clause is used to declare the exception from a method. It gives an indication that the program method can throw an exception. Method can declare multiple exception usingthrows keyword.


 public void parent(){
  try {
      child();
      } catch(MyCustomException e) {  }
  }

public void child throws MyCustomException {
//put some logic so that the exception occurs.
}

Recommend Reading

  1. How java manages Memory?
  2. Why is it advised to use hashcode and equals together?
  3. Comparable and Comparator in java
  4. How to create Singleton class in Java?
  5. Difference between equals and ==?
  6. When to use abstract class over interface?
  7. Difference between final, finally and finalize
  8. Why is it recommended to use Immutable objects in Java