Java Custom Exceptions Tutorial - It's Way Easier Than You Think

Поділитися
Вставка
  • Опубліковано 12 січ 2025

КОМЕНТАРІ • 161

  • @CodingWithJohn
    @CodingWithJohn  2 роки тому +23

    Thanks to Mailgun for sponsoring this video! Head to mailgun.com/john to try Mailgun free today.
    If you have any questions, be sure to ask here!

    • @DaxterSnickers
      @DaxterSnickers 2 роки тому +1

      Nice, you actually did a video for what i asked for. Youre the best, thank you!

  • @turuus5215
    @turuus5215 2 роки тому +45

    I'm reading "Java All in One for Dummies," and I had trouble wrapping my head around the "throwing exceptions" chapter. Thank you for clearing up my confusion. Your lessons are intuitive and straight to the point. Your delivery is amazing.

  • @libertymedicalcommunicatio4908
    @libertymedicalcommunicatio4908 2 роки тому +56

    We’ll done. You’re a natural teacher!

  • @edgardom.7455
    @edgardom.7455 2 роки тому +14

    Hi John, I recently discovered your channel, and I loved the way you expose the content. Learning to program when you are close to 50 years of age, is a much more affordable challenge with the help of channels like yours, thank you very much for your time and dedication. Greetings from Chile.

    • @ravireddyism
      @ravireddyism 2 роки тому +4

      I appreciate your courage coz guys in 20's are finding hard to understand Java but you in your 50's have accepted this challenge to learn java at your age. I wish you all the best and I hope with your dedication and interest you will master it.

  • @blubbfisch98
    @blubbfisch98 Рік тому

    After going through several videos, this is the first truly informational one. No weird jumps, well-spoken English and not a lot of noise around the main topic.
    I know this video is old by now - but keep it up! :P

  • @Adrastus_
    @Adrastus_ 2 роки тому +3

    thanks john. I've been watching more and more of your videos as a java beginner, and as I watch them, each one makes me more certain to get your java bootcamp. these videos are truly great and if im going to learn even more, it will be immensely helpful to know the fundamentals are coming from you.

    • @Achraf_0101
      @Achraf_0101 7 місяців тому

      i have already registered in his bootcamp but there is no problem solving exercices right there we can only watch tutoriels

  • @mustapharaimilawal8053
    @mustapharaimilawal8053 Рік тому

    Hello John, thanks a lot for this video. I watched it some months ago and I missed some points you made about passing Throwable into the custom exception constructor but watching it again now made me realized how detailed this video is. Thanks a lot.

  • @lefruitcake
    @lefruitcake Рік тому

    if you hadn't explained the extends RuntimeException part, wouldn't have saved me in a pinch! Thank you so much!

  • @paranormaledits9526
    @paranormaledits9526 2 роки тому

    Watching this before exam, you're a great teacher.

  • @hummerzone
    @hummerzone 2 роки тому +3

    i love your simple but clear explanations,,thanks John

  • @fcbarcatv-ou4ww
    @fcbarcatv-ou4ww Рік тому

    ive been watching many of your video for the past 3 hours, youre an actual legend

  • @fatmamohmed58
    @fatmamohmed58 2 роки тому

    Before this video i was suffering with Exception but now i find it so easy thank you for your effort

  • @KishoreN-p8s
    @KishoreN-p8s 11 місяців тому

    Brilliant teaching, every word you spoke in this video had intense meaning to it, Thank you

  • @diegoi1313
    @diegoi1313 Рік тому

    Thank you for this well informed video. I was able to complete my assignment after watching it.

  • @sabei221b
    @sabei221b Рік тому

    I'm obsessed with your content, amazing job!!

  • @hunelysium
    @hunelysium 10 місяців тому

    Thank you for making all wonderful videos on Java!! All of them very clarifying!

  • @vn7512
    @vn7512 5 місяців тому

    Your Video always pop up whenever I needed the most! Thank you

  • @ohmohm7884
    @ohmohm7884 10 місяців тому

    Simple, informative, and clear. Brilliant. Thank you!

  • @samreensaleemudeen1220
    @samreensaleemudeen1220 2 роки тому

    love the way you've explained this concept... I didn't learn this properly in C++ so ... I'm really happy that I could understand it so quickly... thank you so for that 😊

  • @aniolmalin
    @aniolmalin 2 роки тому

    that runtime stuffe just solved me a task i thought is difficult, thanks

  • @Abhijeet_Tripathi_
    @Abhijeet_Tripathi_ 2 роки тому

    Struggled with this topic for so long..... You're an amazing teacher 🙌🏻🙌🏻🙇‍♂️.... Thank you so much🙏🏻

  • @enfieldli9296
    @enfieldli9296 2 роки тому

    Wow, cleared some of my confusions, good stuff! Thank you so much John!

  • @jaredschwery167
    @jaredschwery167 2 роки тому +1

    Thanks John! Helpful as always :)

  • @strike_pro_gaming
    @strike_pro_gaming 2 роки тому

    Thanks man.... I'm watching your video from India... it's really helpful

  • @erezswickley2139
    @erezswickley2139 Рік тому

    Amazing. You really helped me wrap my head around this concept. Thank you so much, I really appreciate it.

  • @pipocosounds
    @pipocosounds Рік тому

    Your channel is gold wow!

  • @prasadgujar2007
    @prasadgujar2007 2 роки тому +1

    I purchased your course, however, now i realized you have more detail knowledge on youtube

  • @SaiNadhBolloju
    @SaiNadhBolloju 2 роки тому

    Thanks for your efforts in here… making complex things simple to understand. A request, please explain time and space complexities in your terms.

  • @Righteous_Companions
    @Righteous_Companions 2 роки тому

    Thanks sir 😊 That was helpful 🙂
    I was having trouble making custom exception, Thanks to this video finally its done

  • @ayushkumar-cl7co
    @ayushkumar-cl7co 2 роки тому

    Watched all videos...ur teaching style is awesome.....plz bring videos on Spring Boot

    • @piyushash
      @piyushash 2 роки тому

      Yes, absolutely i am also waiting for Spring boot playlists

  • @ravikumarray338
    @ravikumarray338 2 роки тому +3

    We should neither extend Throwable and nor use it in Catch block. Reason why not to use Throwable in catch block is that it will catch Error also which is not desired .

    • @familyshare3724
      @familyshare3724 2 роки тому +2

      And thus passing Error to custom exception constructor should fail to compile. In other words: Exception cause, not Throwable cause.

    • @boxacuva
      @boxacuva 2 роки тому

      I Agree there is really no need to extend Throwable.

  • @yasminaitmaksene5230
    @yasminaitmaksene5230 2 роки тому

    What a simple way to explain things ! Thank's a lot. 😁😁

  • @matiasmoresi5040
    @matiasmoresi5040 2 роки тому +1

    Hey John!
    Loving all your videos!
    Could you do a tutorial on Streams? 🤩
    Thank you so much!

    • @boxacuva
      @boxacuva 2 роки тому

      I think Streams are a little bit more complex than exception Handling. At least in Theory. But i would recommend u to write all existing Stream Classes down (Sub/Base Classes, Decorators, Reader/Writers,...) and put them in Relation.

  • @nudaykiran2014
    @nudaykiran2014 2 роки тому

    Simple and clear explanation

  • @AnnaAdamczyk
    @AnnaAdamczyk 2 роки тому

    Thank you for another easy to understand video!

  • @ErenYagdran
    @ErenYagdran 2 роки тому

    I'm so fortunate to see a java developer hailing from the last ice age :)

  • @VictorHernandez-qt2xx
    @VictorHernandez-qt2xx 2 роки тому

    Great content. Please add the benefits of catching it in your catch block. Also point out that extending from IllegalArgumentException changes the custom to a runtime excpetion.

  • @lakshyasaharan5348
    @lakshyasaharan5348 2 роки тому +3

    Looking forward to your hair sponsorship.

  • @fabricio.entringer
    @fabricio.entringer 2 роки тому

    Good video. Direct and amazing!

  • @blasm1713
    @blasm1713 2 роки тому

    john john john, your videos are inspiring

  • @mikelkumar6680
    @mikelkumar6680 2 роки тому +1

    Thanks for your work

  • @abdulrashidsinancu1630
    @abdulrashidsinancu1630 11 місяців тому

    How to know if an exception is checked (Compile Time ) or Unchecked (Run Time)
    Ans: If a class extends Exception ->It is known as Compile Time or Checked Exception
    If a class extends RuntimeException ->It is known as RunTime or Unchecked Exception

  • @ayushchakraborty1921
    @ayushchakraborty1921 2 роки тому

    Easy to understand! Will remember the *don'ts* 😂👍🏻

  • @thelinkguys2925
    @thelinkguys2925 2 роки тому

    Wish you have a full spring boot course!

  • @ipodtouch470
    @ipodtouch470 2 роки тому +1

    Could you show exception handling in possibly a larger code base? I understand the concepts but fail to put them into the big picture. For example why use an exception at all instead of an if statement since the possibility of getting a negative age is common .

    • @JorgetePanete
      @JorgetePanete 2 роки тому

      Take for example a method that returns a number that is either valid or broken, how do you check that assuming you don't know what the method does? The method could have instead a BrokenNumberGeneratorException in the method and you could catch it

  • @mebawubeshet6729
    @mebawubeshet6729 20 днів тому

    why donot we simply do private Static void validateAge(int age){
    if(age

  • @pranavkarpe9742
    @pranavkarpe9742 2 роки тому

    Can you make a video on collection framework. Loved the way you explain the concept.

  • @purenepalikancha
    @purenepalikancha 5 місяців тому

    Hi John,
    I have a quick question. Is it correct that if we use an unchecked exception, it is better to surround the exception block with try-catch instead of using throws in the method signature? However, if it is a checked exception, then it is better to use throws in the method's signature.

  • @nikhilagrawal9217
    @nikhilagrawal9217 Рік тому

    Really helpful. Thank you sir.

  • @Speiger
    @Speiger 2 роки тому +1

    I found that mojang used exceptions very weirdly.
    If a network packet is in the wrong thread, they append it in a thread and basically throw a exception that does no logging to stop processing of said network packet.
    (Ignoring the implication on how bad it is to throw hundreds of exception per second, it is still a really interesting concept)

  • @Learn_IT_with_Azizul
    @Learn_IT_with_Azizul Рік тому

    useful content... but I don't like ads, and thanks for time stamps

  • @jovictor3007
    @jovictor3007 2 роки тому

    Thanks, I thought exceptions were some magic, I didnt realise they were just classes.

    • @CodingWithJohn
      @CodingWithJohn  2 роки тому

      Yeah I know what you mean, it feels like such a mystery until you learn that.

  • @slimandahra4294
    @slimandahra4294 2 роки тому

    I will find out..i have eyes 👀 everywhere
    That's funny 😂
    Well done

  • @familyshare3724
    @familyshare3724 2 роки тому +1

    Constructor takes Throwable or Exception cause?

  • @kezug
    @kezug Рік тому

    Is there an inherent overhead (performance degradation of the app) when using Exceptions and Custom Exception handling for "business" error handling as opposed to just putting in validations in code without exception handling? (Assume a large application with many business rules and just trying to come to terms with making a decision of when to use custom Exceptions for business validations vs never)

  • @ruralthunder8854
    @ruralthunder8854 2 роки тому

    Have you ever considered making videos on data structures in Java? Thanks for the videos!

  • @Another0neTime
    @Another0neTime 2 роки тому

    Great explanation.

  • @HanWae363
    @HanWae363 2 роки тому

    If you dont extend exception wouldn't a try catch block also not work if it were trying to catch all Exceptions? Since most exceptions inherit from a root parent Exception?

  • @johngeorge9296
    @johngeorge9296 9 місяців тому

    hey john this tutorial was so informative within a short duration you have covered many important topics! do you offer J2EE and spring related course? besides highfive to you that we have same name....

  • @chetanraj1950
    @chetanraj1950 Рік тому

    Thnak You for this lecture.

  • @sudharshan32nft
    @sudharshan32nft Рік тому

    Thanks John

  • @MehrzweckMandala
    @MehrzweckMandala 6 місяців тому

    Thanks for the video. I'm just wondering: My instructor said regarding "error messages" => Especially with exceptions: Issue clear error messages! Cryptic Java messages about what is wrong where and how in the code are of no interest to the actual user of the program. How do you feel about this?

  • @holdendewit7088
    @holdendewit7088 Рік тому

    Wouldnt using super in the constructor invoke the constructor of the super class (that is to say effectively you have AgeLessThanZeroException e = new InvalidArgumentException(mes, cause); )? If thats the case is there any real benefit to making local object variables and methods instead?

  • @Cemtexify
    @Cemtexify 2 місяці тому

    I'm trying to do unit tests of my project that has a custom exception class and it gives me an error that it triggers the custom exception (I want it to, that's the point of the test).

  • @KolomiecSergeyK
    @KolomiecSergeyK 2 роки тому +1

    Hello, thanks for a nice video. One point that I want to understand, do you think that validation should be handled by exception? As far as I know exception is quite heavy for JVM. Maybe better just return true or false in case something valid or not.

    • @JorgetePanete
      @JorgetePanete 2 роки тому

      exceptions (throwing and not throwing) have gotten lighter at least

  • @DadaKhan1912
    @DadaKhan1912 2 роки тому +1

    Sir, How can we print the custom exception in catch block like e.printStackTrace() or sout(e);

    • @CodingWithJohn
      @CodingWithJohn  2 роки тому +1

      Depends on what you would like to print. sout(e) doesn't give you very much (I haven't tried it until just now, but looks like it just prints the class name of the exception).
      e.printStackTrace is often useful for debugging (although logging tools handle printing the stack trace for an exception their own way in larger applications), so that is more likely what you want. You can also print out the message on your exception if there is one, which you can find at myException.getMessage();

    • @DadaKhan1912
      @DadaKhan1912 2 роки тому

      @@CodingWithJohn Thank you sir for replying for my message with a good explanation 😊

  • @enzokuhlemsotra6383
    @enzokuhlemsotra6383 7 місяців тому

    Mr John what do i need to become a software engineer just like you? meaning after learning java or any other language what are other things that i need to learn in other to become a software engineer.

  • @kamal-xd7id
    @kamal-xd7id Рік тому

    By creating so many custom exceptions, wouldn't it be so unmanageable? Rather we use or define a little more generic or superclass of specific exceptions and pass in the details as param?

  • @LTZMSYAL
    @LTZMSYAL 2 роки тому

    Hi John! Thank's for your great tutos. Could you make a video on the binary search algorithm? Think it would be helpful. Thank's :)

  • @CGDW2
    @CGDW2 2 роки тому +4

    But at which point is it worth it to actually create your own custom Exception rather than just using (going by this example) IllegalArgumentException with a message that says something like "age must be positive".
    Would one ever put additional functionality in a custom Exception? Aside from the comedic value of hilariously named exceptions that your co-workers would hopefully run into (itWasYourJobToImplementThisException), why bother?

    • @stephenJpollei
      @stephenJpollei 2 роки тому +3

      It is probably worth creating your own custom Exception when you can have actual value in using that type in a "catch".
      Maybe an example of potentially good "additional functionality" could be extra fields that store information that "catch" block could use.
      Like a MessageNotReceivedException could take a reference to the message so that the catch block can requeue it.

    • @CGDW2
      @CGDW2 2 роки тому

      @@stephenJpollei Ah right, I can see how that would be useful.

    • @familyshare3724
      @familyshare3724 2 роки тому

      In many backend projects (say microservices with many inputs and outputs), I distinguish between client validation exceptions (invalid external input), upstream exceptions (like database failure), retryable exceptions and non-retryable exceptions. I then want every transaction to have exactly one and only one final status: happy (info) or one fatal exception (log error) type. No matter the service type, it's similar to HTTP or FTP response codes: 200 ok, 404 not found, different 4** client errors, and 5** (this service failed) or upstream/gateway temporary or unrecoverable failure.

    • @familyshare3724
      @familyshare3724 2 роки тому

      Many projects decide whether to handle checked or unchecked exceptions exclusively on day one. Checked Exceptions should be handled immediately by the caller. If a project team (for whatever reason, including lack of discipline) won't consistently handle checked exceptions, then IMO the team should decide to wrap (all) checked exceptions as unchecked (either as a rethrown RuntimeException cause or custom exception extending some runtime exception).
      I recommend a strict consistent pattern, rather than developer whim ("hey this existing exception sounds kinda like it fits our problem"). If you're not sure, then wrap all exceptions as RuntimeException (or a single common custom exception) until you refactor later when/if you do know what you want.

    • @familyshare3724
      @familyshare3724 2 роки тому

      Maybe it's worth noting that many, including architects at Sun, considered the combination of checked and unchecked exceptions a compromise and regrettable failed experiment. Checked exceptions help write reliable fail-proof code. But if not properly understood, not properly handled, checked exceptions often lead to terrible programming habits (like catch and ignore at worst to catch and rethrow at uh, typical annoying tedium). The Throwable, Error, Exception, RuntimeException inheritance structure is a (necessary?) bastardization that also encourages (allows for) poor coding practice (exception mis-handling).

  • @masudulalam2515
    @masudulalam2515 2 роки тому

    How do you handle filter level exceptions which are thrown from filter and can't be caught in @RestControllerAdvice/@ControllerAdvice annotated class?

  • @ivankobyuk8385
    @ivankobyuk8385 2 роки тому

    From Ukrainian dev with huge appreciation! / Від українського розробника з вдячністю!

  • @DeepakSharma-mi8nz
    @DeepakSharma-mi8nz 2 роки тому

    Hey John you are awesome

  • @rasZam
    @rasZam Рік тому

    why did our custom exception extend Exception? why not RuntimeException?

  • @abhineveash
    @abhineveash 11 місяців тому

    Finally got it🎉

  • @sidforreal
    @sidforreal 2 роки тому

    Good to see you finally ditched eclipse 😛😛

  • @yasminaitmaksene5230
    @yasminaitmaksene5230 2 роки тому

    Hello John
    I have a problem trying to use my custom exceptions.
    In some places of my method , when I try to throw a new custom exception, I'm getting this error : Unhandled exception type myCustomException.
    Eclipse suggest to add a try catch block to it.
    Any idea why I'm getting this ?
    Thank's

    • @CodingWithJohn
      @CodingWithJohn  2 роки тому +1

      Any exception you make (unless it's extending RuntimeException) is what's called a checked exception in Java. That means it either had to be declared in the method signature that it can be thrown, or handled with a try/catch.
      Check out my video on checked and unchecked exceptions to learn more!
      ua-cam.com/video/bCPClyGsVhc/v-deo.html

  • @Y3llowMustang
    @Y3llowMustang 2 роки тому

    What VS Code theme is he using?

    • @CodingWithJohn
      @CodingWithJohn  2 роки тому

      This is IntelliJ, with the standard theme. The only change is I darkened the background a little.

  • @Pacvalham
    @Pacvalham 2 роки тому

    throw new NullPointerException();
    //shortcut for throwing a null pointer exception:
    throw null;

  • @olillin
    @olillin 2 роки тому

    Thank you!

  • @keydiram
    @keydiram 2 роки тому

    Hi, Can you add a Maven tutorial? Thanks.

  • @vicke909
    @vicke909 2 роки тому

    Hi, can you do a javaFX tutorial or perhaps a short video showing how to begin? Thank you : )

  • @amirulidzham
    @amirulidzham 2 роки тому

    Hi John. Thank you for such a great video. Really appreciate it. I just have one question, sorry that it's not related to video, is there any way to have a dynamic set attribute in OOP? I'm kinda interested like what offered in Laravel's Eloquent method (the insert method). All you need to do is create new object, set attribute object from instance, call save method. Not sure if Spring has something to like this to offer.

    • @paveljavorek2076
      @paveljavorek2076 2 роки тому +1

      Hi
      Not sure if is this the answer you looking for, but spring boot contains Spring Data JPA, when you can save atribute or objects to the database throught repository object

    • @amirulidzham
      @amirulidzham 2 роки тому +1

      @@paveljavorek2076 wow. I gotta try it out myself. Thanks for the valuable information.

    • @boxacuva
      @boxacuva 2 роки тому

      This Question is a little bit confusing. Do you mean an ORMapper like EF/NHibernate or do you mean aop? Or Simply dynamic Keyword like in c#.

    • @amirulidzham
      @amirulidzham 2 роки тому

      @@boxacuva I've no idea of what are you talking. It not confusing at all. Maybe you should take a look at Laravel first specifically at eloquent method of saving data

    • @boxacuva
      @boxacuva 2 роки тому +1

      @@amirulidzham wdym its just a normal ORMapper Feature.
      Maybe it would help to explain what that feature does instead of letting ppl looking it up for you. So they can help.
      I just gonna assume its a normal CRUD transaction done in a higher level langugage.
      Edit: Just googled it and found a php ORMapper. Not sure if that is what u asking for. So gl

  • @MariusSipanu
    @MariusSipanu 2 роки тому

    Very good video

  • @timm1328
    @timm1328 2 роки тому

    Extending Exception is usually a bad idea. Checked exceptions were a failed experiment and only leads to empty global catch clauses strewn through the code. Instead custom exceptions can extend RuntimeException. Furthermore throws clauses on methods are a pain in the ass when trying to pass method references.

  • @alisbai4376
    @alisbai4376 Рік тому

    have anybody noticed the font colors in Intellij mach the Java logo colors?

  • @Sudheer_662
    @Sudheer_662 2 роки тому

    hi john ,can u pls make a video on java Streams api

  • @javalady
    @javalady 8 місяців тому

    Thanks that was really usefull

  • @adibpeerzade5657
    @adibpeerzade5657 2 роки тому

    can you put videos on jdbc?

  • @berkcanulubas1318
    @berkcanulubas1318 8 місяців тому

    thank you for th great videos

  • @xxxguruji5211
    @xxxguruji5211 2 роки тому

    Thank you .

  • @mohannadarslan2478
    @mohannadarslan2478 Рік тому

    Thank you

  • @Eva-kt3tu
    @Eva-kt3tu Рік тому

    thank you so much

  • @socaljusticewarrior558
    @socaljusticewarrior558 2 роки тому +1

    I like the part where you point at the camera and go out of focus and then come back. That was very cinematic.

    • @CodingWithJohn
      @CodingWithJohn  2 роки тому

      Yep, new camera! Besides that part, it's pretty hard to tell the difference between this and all my other videos which were just recorded with a phone.

  • @azamvlogs84
    @azamvlogs84 Рік тому

    Anyone know which eclipse is he using??

  • @blacksheep1337
    @blacksheep1337 2 роки тому

    nice u a real goood teacher

  • @jagathis2863
    @jagathis2863 2 роки тому

    Hii sir please upload the tic tac toe dynamic size java program?

  • @s6031417
    @s6031417 2 роки тому

    YES

  • @LeafyConversations
    @LeafyConversations 2 роки тому

    You are awesome!!!!!

  • @luwamabraham4338
    @luwamabraham4338 Рік тому

    I don't now how to thank you. GBU