Войти
  • 207531Просмотров
  • 2 года назадОпубликованоTelusko

#80 Exception throw keyword in Java

Check out our courses: Java Spring Boot AI Live Course: Coupon: TELUSKO20 (20% Discount) AI Powered DevOps with AWS - Live Course :- Coupon: TELUSKO20 (20% Discount) Master Java Spring Development : Coupon: TELUSKO20 (20% Discount) For More Queries WhatsApp or Call on : +919008963671 website : Udemy Courses: Spring: Java:- Java Spring:- Java For Programmers:- Python : Git : Docker : Instagram : Linkedin : TELUSKO Android App : TELUSKO IOS App : Discord : In this lecture we are discussing throw keyword : #1 -- throw keyword in Java is used to explicitly throw an exception. When an exception is thrown using the throw keyword, the execution of the current method is stopped. syntax- throw new NullPointerException("Object is null"); e.g public void divide(int a, int b) { if (b == 0) { throw new ArithmeticException("Cannot divide by zero"); } int result = a / b; (result); } #2 -- throw keyword is used to throw exceptions, not to catch them. To catch exceptions, you need to use a try-catch block. -- if you do not use try-catch then the control is passed, where the method is called. -- when you want to pass message to an exception then you should use the parametrized constructor instead non parameterized constructor e.g class Main{ public static void main(String []args){ int a=0; try{ if(a==0) throw new ArithmeticException("a should not be zero"); // throw new ArithmeticException() is non parametrized constructor } catch(ArithmeticException e){ ("Exception caught: "+e); } } } Output: Exception caught: : a should not be zero class Main{ public static void main(String[] args){ int j=30; int i=1; try{ j=18/i; //handle the exception using throw if(j==0) throw new ArithmeticException("i donot want to print 0"); //try to create an exception } catch(ArithmeticException e){//here catch is catching the exception ("ArithmeticException caught"); ( ()); //getMessage() method use to get the message } catch(Exception e){ ("Exception caught"); } } } Github repo : More Learning : Java :- Python :- Django :- JavaScript :- Node JS :- Rest Api :- Servlet :- Spring Framework :- Design Patterns in Java :- Docker :- Blockchain Tutorial :- Corda Tutorial:- Hyperledger Fabric :- NoSQL Tutorial :- Mysql Tutorial :- Data Structures using Java :- Git Tutorial :- Donation: PayPal Id : navinreddy20