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

  Рет қаралды 142,243

Coding with John

Coding with John

Күн бұрын

Full tutorial on creating custom exceptions in Java!
Thanks to Mailgun for sponsoring this video! Head to mailgun.com/john to try Mailgun today.
Complete Java course: codingwithjohn.thinkific.com/...
Custom exceptions can be intimidating if you're relatively new to Java. But creating your own Java exceptions is way easier than you may think.
If you're confused about how to go about creating your own exceptions in Java, or to find out best practices for doing so, you're in the right place!
Learn or improve your Java by watching it being coded live!
Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.
Let me know what else you'd like to see!
Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.
📕 THE best book to learn Java, Effective Java by Joshua Bloch
amzn.to/36AfdUu
📕 One of my favorite programming books, Clean Code by Robert Martin
amzn.to/3GTPVhf
🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
www.audibletrial.com/johnclean...
🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
bit.ly/3QPNGko
📹Phone I use for recording:
amzn.to/3HepYJu
🎙️Microphone I use (classy, I know):
amzn.to/3AYGdbz
Donate with PayPal (Thank you so much!)
www.paypal.com/donate/?hosted...
☕Complete Java course:
codingwithjohn.thinkific.com/...
codingwithjohn.com

Пікірлер: 153
@CodingWithJohn
@CodingWithJohn Жыл бұрын
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 Жыл бұрын
Nice, you actually did a video for what i asked for. Youre the best, thank you!
@libertymedicalcommunicatio4908
@libertymedicalcommunicatio4908 Жыл бұрын
We’ll done. You’re a natural teacher!
@turuus5215
@turuus5215 Жыл бұрын
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.
@Adrastus_
@Adrastus_ Жыл бұрын
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.
@mustapharaimilawal8053
@mustapharaimilawal8053 11 ай бұрын
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.
@enfieldli9296
@enfieldli9296 Жыл бұрын
Wow, cleared some of my confusions, good stuff! Thank you so much John!
@hummerzone
@hummerzone Жыл бұрын
i love your simple but clear explanations,,thanks John
@samreensaleemudeen1220
@samreensaleemudeen1220 Жыл бұрын
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 😊
@Abhijeet_Tripathi_
@Abhijeet_Tripathi_ Жыл бұрын
Struggled with this topic for so long..... You're an amazing teacher 🙌🏻🙌🏻🙇‍♂️.... Thank you so much🙏🏻
@hunelysium
@hunelysium 2 ай бұрын
Thank you for making all wonderful videos on Java!! All of them very clarifying!
@jaredschwery167
@jaredschwery167 Жыл бұрын
Thanks John! Helpful as always :)
@blubbfisch98
@blubbfisch98 4 ай бұрын
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
@sabei221b
@sabei221b 8 ай бұрын
I'm obsessed with your content, amazing job!!
@ohmohm7884
@ohmohm7884 2 ай бұрын
Simple, informative, and clear. Brilliant. Thank you!
@erezswickley2139
@erezswickley2139 Жыл бұрын
Amazing. You really helped me wrap my head around this concept. Thank you so much, I really appreciate it.
@fatmamohmed58
@fatmamohmed58 Жыл бұрын
Before this video i was suffering with Exception but now i find it so easy thank you for your effort
@fcbarcatv-ou4ww
@fcbarcatv-ou4ww Жыл бұрын
ive been watching many of your video for the past 3 hours, youre an actual legend
@user-yr4bu7gm9s
@user-yr4bu7gm9s 3 ай бұрын
Brilliant teaching, every word you spoke in this video had intense meaning to it, Thank you
@AnnaAdamczyk
@AnnaAdamczyk Жыл бұрын
Thank you for another easy to understand video!
@yasminaitmaksene5230
@yasminaitmaksene5230 Жыл бұрын
What a simple way to explain things ! Thank's a lot. 😁😁
@edgardom.7455
@edgardom.7455 Жыл бұрын
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 Жыл бұрын
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.
@SUMITYADAV-cy9hf
@SUMITYADAV-cy9hf 10 ай бұрын
you made java so easy man ..thanks for your contribution
@mikelkumar6680
@mikelkumar6680 Жыл бұрын
Thanks for your work
@aniolmalin
@aniolmalin Жыл бұрын
that runtime stuffe just solved me a task i thought is difficult, thanks
@nikhilagrawal9217
@nikhilagrawal9217 4 ай бұрын
Really helpful. Thank you sir.
@nudaykiran2014
@nudaykiran2014 Жыл бұрын
Simple and clear explanation
@SaiNadhBolloju
@SaiNadhBolloju Жыл бұрын
Thanks for your efforts in here… making complex things simple to understand. A request, please explain time and space complexities in your terms.
@diegoi1313
@diegoi1313 8 ай бұрын
Thank you for this well informed video. I was able to complete my assignment after watching it.
@pranavkarpe9742
@pranavkarpe9742 Жыл бұрын
Can you make a video on collection framework. Loved the way you explain the concept.
@chetanraj1950
@chetanraj1950 10 ай бұрын
Thnak You for this lecture.
@lefruitcake
@lefruitcake Жыл бұрын
if you hadn't explained the extends RuntimeException part, wouldn't have saved me in a pinch! Thank you so much!
@sudharshan32nft
@sudharshan32nft 8 ай бұрын
Thanks John
@paranormaledits9526
@paranormaledits9526 Жыл бұрын
Watching this before exam, you're a great teacher.
@VictorHernandez-qt2xx
@VictorHernandez-qt2xx Жыл бұрын
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.
@fabricio.entringer
@fabricio.entringer Жыл бұрын
Good video. Direct and amazing!
@preetamvarun9219
@preetamvarun9219 6 ай бұрын
Thank you!
@Righteous_Companions
@Righteous_Companions Жыл бұрын
Thanks sir 😊 That was helpful 🙂 I was having trouble making custom exception, Thanks to this video finally its done
@CodingWithJohn
@CodingWithJohn Жыл бұрын
Not so hard once you know!
@Another0neTime
@Another0neTime Жыл бұрын
Great explanation.
@SayanRick100
@SayanRick100 Жыл бұрын
Thanks man.... I'm watching your video from India... it's really helpful
@pipocosounds
@pipocosounds Жыл бұрын
Your channel is gold wow!
@Eva-kt3tu
@Eva-kt3tu 4 ай бұрын
thank you so much
@thelinkguys2925
@thelinkguys2925 Жыл бұрын
Wish you have a full spring boot course!
@matiasmoresi5040
@matiasmoresi5040 Жыл бұрын
Hey John! Loving all your videos! Could you do a tutorial on Streams? 🤩 Thank you so much!
@boxacuva
@boxacuva Жыл бұрын
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.
@LTZMSYAL
@LTZMSYAL Жыл бұрын
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 :)
@abhineveash
@abhineveash 3 ай бұрын
Finally got it🎉
@mohannadarslan2478
@mohannadarslan2478 11 ай бұрын
Thank you
@ruralthunder8854
@ruralthunder8854 Жыл бұрын
Have you ever considered making videos on data structures in Java? Thanks for the videos!
@xxxguruji5211
@xxxguruji5211 Жыл бұрын
Thank you .
@javalady
@javalady 6 күн бұрын
Thanks that was really usefull
@johngeorge9296
@johngeorge9296 Ай бұрын
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....
@berkcanulubas1318
@berkcanulubas1318 19 күн бұрын
thank you for th great videos
@ayushchakraborty1921
@ayushchakraborty1921 Жыл бұрын
Easy to understand! Will remember the *don'ts* 😂👍🏻
@developer9049
@developer9049 3 ай бұрын
Thanks :)
@DeepakSharma-mi8nz
@DeepakSharma-mi8nz Жыл бұрын
Hey John you are awesome
@blasm1713
@blasm1713 Жыл бұрын
john john john, your videos are inspiring
@ayushkumar-cl7co
@ayushkumar-cl7co Жыл бұрын
Watched all videos...ur teaching style is awesome.....plz bring videos on Spring Boot
@piyushash
@piyushash Жыл бұрын
Yes, absolutely i am also waiting for Spring boot playlists
@MariusSipanu
@MariusSipanu Жыл бұрын
Very good video
@samuelbullon3792
@samuelbullon3792 Жыл бұрын
loved it
@LeafyConversations
@LeafyConversations Жыл бұрын
You are awesome!!!!!
@s6031417
@s6031417 Жыл бұрын
YES
@vicke909
@vicke909 Жыл бұрын
Hi, can you do a javaFX tutorial or perhaps a short video showing how to begin? Thank you : )
@prasadgujar2007
@prasadgujar2007 Жыл бұрын
I purchased your course, however, now i realized you have more detail knowledge on youtube
@ravikumarray338
@ravikumarray338 Жыл бұрын
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 Жыл бұрын
And thus passing Error to custom exception constructor should fail to compile. In other words: Exception cause, not Throwable cause.
@boxacuva
@boxacuva Жыл бұрын
I Agree there is really no need to extend Throwable.
@blacksheep1337
@blacksheep1337 Жыл бұрын
nice u a real goood teacher
@Sudheer_662
@Sudheer_662 Жыл бұрын
hi john ,can u pls make a video on java Streams api
@Speiger
@Speiger Жыл бұрын
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)
@KolomiecSergeyK
@KolomiecSergeyK Жыл бұрын
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 Жыл бұрын
exceptions (throwing and not throwing) have gotten lighter at least
@lakshyasaharan5348
@lakshyasaharan5348 Жыл бұрын
Looking forward to your hair sponsorship.
@Learn_IT_with_Azizul
@Learn_IT_with_Azizul 7 ай бұрын
useful content... but I don't like ads, and thanks for time stamps
@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)
@ipodtouch470
@ipodtouch470 Жыл бұрын
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 Жыл бұрын
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
@masudulalam2515
@masudulalam2515 Жыл бұрын
How do you handle filter level exceptions which are thrown from filter and can't be caught in @RestControllerAdvice/@ControllerAdvice annotated class?
@luwamabraham4338
@luwamabraham4338 Жыл бұрын
I don't now how to thank you. GBU
@keydiram
@keydiram Жыл бұрын
Hi, Can you add a Maven tutorial? Thanks.
@rasZam
@rasZam 8 ай бұрын
why did our custom exception extend Exception? why not RuntimeException?
@HanWae363
@HanWae363 Жыл бұрын
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?
@familyshare3724
@familyshare3724 Жыл бұрын
Constructor takes Throwable or Exception cause?
@holdendewit7088
@holdendewit7088 11 ай бұрын
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?
@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?
@ErenYagdran
@ErenYagdran Жыл бұрын
I'm so fortunate to see a java developer hailing from the last ice age :)
@amirulidzham
@amirulidzham Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@paveljavorek2076 wow. I gotta try it out myself. Thanks for the valuable information.
@boxacuva
@boxacuva Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@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
@joelpww
@joelpww Жыл бұрын
God sent
@azamvlogs84
@azamvlogs84 9 ай бұрын
Anyone know which eclipse is he using??
@slimandahra4294
@slimandahra4294 Жыл бұрын
I will find out..i have eyes 👀 everywhere That's funny 😂 Well done
@yasminaitmaksene5230
@yasminaitmaksene5230 Жыл бұрын
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 Жыл бұрын
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! kzbin.info/www/bejne/mHSzdJ-vfNiJnsU
@Pacvalham
@Pacvalham Жыл бұрын
throw new NullPointerException(); //shortcut for throwing a null pointer exception: throw null;
@adibpeerzade5657
@adibpeerzade5657 Жыл бұрын
can you put videos on jdbc?
@jovictor3007
@jovictor3007 Жыл бұрын
Thanks, I thought exceptions were some magic, I didnt realise they were just classes.
@CodingWithJohn
@CodingWithJohn Жыл бұрын
Yeah I know what you mean, it feels like such a mystery until you learn that.
@jagathis2863
@jagathis2863 Жыл бұрын
Hii sir please upload the tic tac toe dynamic size java program?
@alisbai4376
@alisbai4376 4 ай бұрын
have anybody noticed the font colors in Intellij mach the Java logo colors?
@DadaKhan1912
@DadaKhan1912 Жыл бұрын
Sir, How can we print the custom exception in catch block like e.printStackTrace() or sout(e);
@CodingWithJohn
@CodingWithJohn Жыл бұрын
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 Жыл бұрын
@@CodingWithJohn Thank you sir for replying for my message with a good explanation 😊
@sidforreal
@sidforreal Жыл бұрын
Good to see you finally ditched eclipse 😛😛
@CGDW2
@CGDW2 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@stephenJpollei Ah right, I can see how that would be useful.
@familyshare3724
@familyshare3724 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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).
@abdulrashidsinancu1630
@abdulrashidsinancu1630 3 ай бұрын
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
@timm1328
@timm1328 Жыл бұрын
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.
@Y3llowMustang
@Y3llowMustang Жыл бұрын
What VS Code theme is he using?
@CodingWithJohn
@CodingWithJohn Жыл бұрын
This is IntelliJ, with the standard theme. The only change is I darkened the background a little.
@belayketema9921
@belayketema9921 Жыл бұрын
Wow
@ivankobyuk8385
@ivankobyuk8385 Жыл бұрын
From Ukrainian dev with huge appreciation! / Від українського розробника з вдячністю!
@larryd9577
@larryd9577 Жыл бұрын
NegativeAgeException.
@CodingWithJohn
@CodingWithJohn Жыл бұрын
Even better!
@socaljusticewarrior558
@socaljusticewarrior558 Жыл бұрын
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 Жыл бұрын
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.
Checked vs. Unchecked Exceptions in Java Tutorial - What's The Difference?
10:14
Did you find it?! 🤔✨✍️ #funnyart
00:11
Artistomg
Рет қаралды 110 МЛН
У мамы в машине все найдется
00:38
Даша Боровик
Рет қаралды 2,1 МЛН
Когда на улице Маябрь 😈 #марьяна #шортс
00:17
Java File Input/Output - It's Way Easier Than You Think
8:18
Coding with John
Рет қаралды 416 М.
Optionals In Java - Simple Tutorial
15:53
Coding with John
Рет қаралды 192 М.
Java Exception Handling Tutorial
11:39
Keep On Coding
Рет қаралды 79 М.
Exception Handling in Java Tutorial
13:20
Coding with John
Рет қаралды 347 М.
How To Call a REST API In Java - Simple Tutorial
29:14
Coding with John
Рет қаралды 249 М.
Lambda Expressions in Java - Full Simple Tutorial
13:05
Coding with John
Рет қаралды 688 М.