Exception handling throws and throw in java

Using throws

                If a method or constructor throws an exception instead of handling it, It makes a developer to use try catch when they are using it.

Try catch is optional if an exception thrown is Unchecked or ERROR.


	void divide(int I, int k) throws ArithmeticException
		// you logic has a possibility of throwing ArithmeticException


 Developer who access this method should take the responsibility of handling it or throwing it.


Throwing an Exception

Throw keyword can be used to throw an exception manually, using throw keyword you can avoid execution of code that fails in future due to exception.

void divide(int i, int j) 
		if (j == 0) // you can prevent rest of the code from execution if your program has Arithmetic exception
			throw new ArithmeticException();
		// more code
		int k = i / j;

Related Post