top of page
Writer's pictureRosario Riley

What is the difference between try-catch and throw?tccicomputercoaching.com

An exception is an event that occurs during the execution of programs. ... Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.

Exception handling is built upon three keywords: try, catch, and throw.

In simple Way try is used for RISKY CODE where a programmes can think that There may be a chance Of occurring Exception then Programmer will use try block and if there is any Exception occurs like (Division /O) then it will Throw that exception to CATCH block and Catch is use to verify exception type and Handle It. #Every try must have at least 1 Catch or finally or Both.. #Throws block never handle any exception It only Delegate the Exception to Main method or Caller method..

Try - Catch: Syntax

try { //Protected code }catch(ExceptionName e1) { //Catch block }

The throw keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch block). The throws keyword in the method prototype is used to specify that your method might throw exceptions of the specified type.

Throw: Syntax

public class TestThrow1{

static void validate(int age){

if(age<18)

throw new ArithmeticException("not valid");

else

System.out.println("welcome to vote");

}

public static void main(String args[]){

validate(21);

System.out.println("rest of the code...");

}

To know more in detail about Exception Handling in C++, Java and Python.

Join class at TCCI Computer Coaching in Bopal and Satellite in Ahmedabad.

Call us @ 9825618292

Visit us @ http://tccicomputercoaching.com/

0 views0 comments

Recent Posts

See All

Comments


bottom of page