Custom Exception is never thrown in body of corresponding try statement. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Custom Exception is never thrown in body of corresponding try statement.

I had created two programs P1 and P2. In P1 program haven't create any custom Exception class and the program execute successfully. But in case of P2 program i had created a my own custom class and extending Exception class and also call super in my no-arg constructor. But the program not compiled. I would like to know why I'm getting complier time error in P2 Program. https://code.sololearn.com/czjoqMHJ34vg/?ref=app https://code.sololearn.com/cwDH1wyRsP18/?ref=app

28th Jul 2020, 6:57 PM
P∆WAN M∆URY∆
P∆WAN M∆URY∆ - avatar
6 Answers
+ 2
As try statement never thrown any exception thats why when it's extended and called the exception class which is never initiated in the try block that's why it's throwing that error by java compiler because compiler knows that you are trying to catch an exception which is never thrown in try block. That's what thr possible reason for the error if I'm wrong than correct me...
28th Jul 2020, 7:15 PM
Preity
Preity - avatar
+ 2
Jayakrishna🇮🇳 Preity in The Program P1 I didn't throw any exceptions but still P1 compiled and execute.
28th Jul 2020, 7:19 PM
P∆WAN M∆URY∆
P∆WAN M∆URY∆ - avatar
+ 2
Jayakrishna🇮🇳 i didn't get you sorry!. In actual for P2 program. I extends the Exception class already and also called the constructor. It's should be the same behaviour. But it's not like that here.
28th Jul 2020, 7:28 PM
P∆WAN M∆URY∆
P∆WAN M∆URY∆ - avatar
+ 1
As error saying, you should add throwing mechanism for that custom exception. try{ System.out.println("I will not throw any exception!"); throw new CustomException(); //add this } catch (CustomException e) { }
28th Jul 2020, 7:16 PM
Jayakrishna 🇮🇳
+ 1
P∆WAN M∆URY∆ there you are using predefined in-built exception. Java compiler recognise those but for custom exception, you must put a throwing condition to handle that exception. Otherwise it has no meaning...
28th Jul 2020, 7:23 PM
Jayakrishna 🇮🇳
0
Sry forget to reply, hope it is solved now...??
30th Jul 2020, 6:16 PM
Jayakrishna 🇮🇳