Exception Handling In Java | Exception Handling In Java With Examples | Java Tutorial | Edureka
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703130687_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Exception Handling In Java | Exception Handling In Java With Examples | Java Tutorial | Edureka
Hey guys this is Neha from mad Eureka and I welcome you all to the session on exception handling in Java errors happen at any time but what matters is the way we handle and rectify them to maintain the normal flow Java being the most prominent object-oriented language provides a powerful mechanism to handle
These errors and exceptions and effective exception handling makes your program more robust and easier to debug in this session I will talk about the fundamentals and various methods of Java exception handling let’s look at the topics to be covered in this session first and foremost I will tell you what
Exception handling is then I will give you a comparison between errors and exceptions next I will give you an overview on exceptions hierarchy and you will also understand the difference between checked and unchecked exceptions after understanding these fundamentals let’s hook in to the programming part and learn the basic syntax of exception
Handling once we are done with the basic syntax then I will be explaining you the types of exceptions in depth after that we will dive into the various methods of exception handling along with examples and I will wrap up the session by giving you a difference between throw and
Throws and also between final finalize and finally also we will be seeing about custom exceptions and how to pass an exception so let’s begin the discussion and see what exception handling is exception is a problem that arises during the execution of a program it can occur for many different reasons say a
User has entered an invalid data or a file that needs to be opened cannot be found or you can also say that a network connection that has been lost in the middle of communications or the JVM has run out of memory many such cases but if
We do not handle them it leads to a system failure so handing an exception is very important and that’s where Java introduced exception handling mechanism to handle the runtime errors so that the normal execution flow will not be for example glass not found our exception SQL exception etc now let’s
Move ahead and see the difference between error and exception first errors are impossible to recover but exception can be recovered by handling them next errors are of type unchecked but exceptions can be either checked or unchecked type just wait a little while and you will no word I’ll check the none
Check type of exceptions and errors are something that happened at runtime but exception can happen either at compile time or runtime exceptions are caused by application itself whereas errors are caused by the environment on which the application is running so these are the key points of difference between errors
And exceptions now let’s see what is exception hierarchy all exceptions and errors types are subclasses of class throwable which is the base class of hierarchy here one branch is headed by exception that is this class is used for exceptional conditions that user program should catch for example say nullpointerexception runtime exception
Etc and other branch error are used by the java runtime system to indicate the errors that has to do with the runtime environment itself that is JRE for example virtual machine error or stack overflow error etc so how Java Virtual Machine handles exceptions whenever inside a method if an exception has
Occurred then the method creates an object known as exception object and hands it off for the runtime system and this exception object contains name and description of the exception and also the current state of the program where exception has occurred and creating the exception object and handling it to the
Runtime system is called throwing an exception then using try catch finally methods these exceptions can be handled so this is how Java Virtual Machine handles exceptions internally next let’s say that differences between checked and unchecked exceptions and simple terms exceptions that happen at compile time or check that
Options like our exceptions etc and runtime exceptions are called unchecked exceptions like / 0 re out of bound nullpointerexception etc basically unchecked exceptions are built-in exceptions in Java so check the exceptions cannot be simply ignored the programmer should handle these exceptions and runtime exceptions are ignored at the time of compilation now
Let’s see the basic example of exception so here I have defined the class and inside the main method I have a try block so in this try block the code that we are going to right mirror is an exception that is it contains the code that raised exception and then the
Raised exception will be handled in the cash flow so let’s see a small program as how it occurs first I will create a new package called exception Ida Rico and now I create a new class called sample exception finish so inside the class the first thing that
We are going to do is we are going to write the main method so here I’ll create a string STR and make it as null so now after this I will try to retrieve the length of the string so when I execute this program it will throw an exception why because the
String is none and we are trying to retrieve the length of the string as I said throws nullpointerexception because the string is null it does not contain any values so now let’s use try and catch method to handle this exception so what I’m going to do here and try
Block I’m going to write the code that will raise an exception say I have given a a 30 and B are zero now I will try to divide a number by zero like in C is equal to a by B so just tell me what
Happens here now say if we try to divide a number by zero then it says we cannot divide the number by zero because it raised an arithmetic exception correct so let’s see how that occurs now as a throws an exception here so what I will do to maintain the normal
Flow of execution I will write the cash block to handle this exception that is okay let’s run the program and see the output so as I told the exception has been catched by catch flock so here first it will throw the exception and then it goes to the cache block cache block
Handles the arithmetic exception II so it prints cannot divide a number by zero so this is how exception handling works now let’s say the various types of exceptions so in Java there are two types of exceptions one built-in exceptions and the other one user-defined exceptions first let’s see
What is built-in exceptions these are the exceptions which are available in Java libraries and they are suitable to explain certain error situations like arithmetic exception array index out of bounds exception class not form IO exception run by mix search number format etc so let’s see an example and understand how built-in exception works
So this example is one type of exception that there’s automatic exception where we try to divide the number by zero and it results in arithmetic exception and we have catch the method so let’s see one more example of that kind now I’ll use one more try block
Here what I’m going to do is I’m going to declare an integer number and try to pass a string variable so what happens it’s an obvious fact that it throws an exception so let’s see how so just tell me one thing I have declared an integer number and trying to
Parse a string variable so what happens it obviously throws exception now in order to maintain the normal flow we have to handle this exception so I’ll use a catch block and handle the number format exception so now let’s execute and see first it said cannot divide by zero because we handle arithmetic exception
And next we handle number format exception next we will see how array index out of bounds exception occurs and how it can be handled so here you can see I have created an area of size five and now I’ll try to access the seventh element in the array
So what happens after this it will obviously throw an exception by because the size of the array is Phi and I’m trying to access the array that is out of bound so what happens when I catch the exception it says array index out of bounds exception you
Sorry this array index out of bounds now again let’s execute as I said again the array index out of bounds exception got handle and it printed the output so this is how built-in exceptions are present in Java libraries so now I will jump into that methods of exceptions because you need
To know the throw and throws methods to understand user-defined exceptions after I complete the methods of exceptions I will explain you the user-defined exceptions so these are the various methods of exceptions that is try catch finally throw and throws let’s see each of them first try try block is used to
Enclose the code that métro exception the syntax is as follows as you have already seen it’s very simple we write a code that throws exception and we can handle it using the catch block next nested try nested try block is nothing but a try within a try block for example
You can see here I have declared 1 try and inside that I have created one more try catch and there is one more try as well so let’s see a small example as how it works so do one thing here I will give a try block within a try block and then after
Catch I will end the statement and after that I will print like system dot out dot println let’s print some other statement you just look at the program first what I did so from here I have modified the program I have given one try block and
Inside one try block I have given one more try and catch block okay and now I have created one more try catch and handled here after that what I am doing I am just giving a statement as print the other statement after that I am closing this try block then I am again
Catching the exception and handling.that okay so within this one try block there are two try blocks so that’s how nested try can be used so let’s see the output see first it’s saying that cannot divide by zero because it was the first thing that we have done and within the try
Block it said number format exception because the first try block got executed and next for this one more exception that it throwed it says it handle and again is printed other statement that’s all because we are not declaring anything in the other try block that is
The main try block so it is not printing that exception if this try block has thrown any exception again that would have been printed but as there is nothing that’s not printing so this is a usage of nested try and how it can be declared and this is how it works
Now let’s see the usage of catch block as in these previous examples you have already seen how it can be used and there’s also one more thing that this multi catch that is if you have to perform various tasks at the occurrence of various exceptions then you can use
Java multi cache block so here you can see you have one try block and have multiple catch blocks so let’s see how that works and modifies this program only for you so here I have one try block and I have two different catch blocks let’s execute and see
So first it printed number format exception and then it printed other statement by this exception did not get handle because there was no any exception that was being thrown for this okay if there was any exception that was thrown then would have been handled so this is how you can use multiple catch
Blocks next we’ll see finally finally is a block that is used to execute important codes such as closing connection stream etc no matter whether exception is handled or not finally block will always be executed so in the previous example you saw that after declaring a try block you must use cache
Block to maintain the normal flow but when using finally block the catch block is not required let’s see how I’ll do one thing I will remove all the catch blocks here so I just have a try block now I will give finally and printer statement
So now let’s execute this as I said we have not used cash flow it throws the exception but even on throwing the exception the flow will not be disrupted there because we have used finally block to execute the code so you can see the finally block is always executed so
That’s how it works next let’s see what is throw throw is nothing but a keyword which is used to throw an exception so you can see the syntax here inside a method you are throwing the exception let’s see how it throws an exception let’s modify this program
First I will define the function here so inside the throw block I am going to throw an arithmetic exception okay now let’s handle the exception using catch block I’ll close this average function and call this function in the main method so first I trow the exception in
Triblock and catched it and now I’m calling the entire function in the main method so let’s see what will be the output it’s just a limb the exception is being caught correct why because when we call the average function in the main method it goes back to the loop the
Exception will be throat but it has been catched correct so this is how Troy is used to throw an exception and it can be handled in the cache block simple let’s see what Astros throws is also a keyword which is used to declare the exceptions it does not throw any exception but it
Specifies that there may occur any exception in the method and it is always used with the method signature let’s see how again I’ll modified this program itself as I have told it is used with method signature I’m going to use a throws keyword along with the method
And I’m also using a throw keyword to throw the arithmetic exception now inside the main method I will use a try block so this is an example where then I’m using the troll keywords along with the method signature and inside this I’m drawing a new exception but when I’m
Calling the method or a function inside the try block in main method it will throw an exception so instead of handling it I am just printing the finally below so let’s see what happens so you can see here first the inside average function is printed and then it
Says that there is an exception in the main method that is we are throwing an exception as we are not handling that at the end it’s printing the finally block simple so this is how throws is used next let’s see the difference between throw and throws first throw is
Explicitly used to throw an exception but throws is used to declare an exception we have already seen how it worked next check the exceptions cannot be propagated using only throw but checked exceptions can be propagated using throws throw is followed by an instance and throws is followed by a class and
Draw is always used within a method and throws is used with the method signature and throw can throw only one exception and not multiple exceptions and throws can declare multiple exceptions just now we saw how it worked next we’ll see the difference between final finally and finalize so final as
The keyword finally is a block as we saw and finalized as a method final is used to apply restrictions and class methods and variables but finally is used to place an important code and finalize is used to perform cleaner processing just before the object is garbage collected
Coming to final the final class cannot be inherited and the final method cannot be overridden and the final variable cannot be changed coming to finally it will be executed whether the exception is handled or not we already saw how it worked now let’s see a user-defined exception sometimes the buildin exceptions in Java
Are not able to describe a certain situation in such cases a user can also create exceptions and that are called as user-defined exceptions there are two important points first one a user-defined exception must extend the exception class the second one the exception is thrown using a throw
Keyword so let’s see how it works I’ll modify the same program first inside the try block I’ll throw an exception using throw keyword I will handle the exception using catch block I’ll close the class now I will extend the exception using extends class so let’s bar some argument here and
Let’s try to print output so let’s parse um our cumin as we have throat a new exception and then I’m extending my exception then what happens let’s see have saved the program and I’m giving the value of A to B okay now let’s see what will be the output as expected it
Should print the value as five let’s see whether it prints the same prescribed value or not exactly they got the output as desired that is the throw keyword is used to create a new exception and throw it to the cash flow and then it got handled and vendor and when extending that we
Will get the same desired output so this is how you can create a user-defined exception now coming to the end of the discussion let’s see what our custom exceptions and how to parse an exception and modify the same program again you so in this case if the number that we
Entered is more than hundred then it should throw an exception else it should print the provided input is valid let’s see how after that I’m reading a number here and then trying to validate the input and try block if the input is not validated then it will be handled in the
Cash flow again this is a user-defined exception so it must extend the exception to us so this is how I have created custom exception so let’s run the program and check what will be the output so it’s asking to end the number that is less than hundred so I’ll enter 99 says
Valid input again I’ll run the program now I’ll enter 101 it says input is greater than 100 and it caught the exception that as I have mentioned here if the number is greater than 100 then it should throw an exception and that exception is caught in the cash flow so
This is how custom exception can be used in Java now let’s also see how to pass an exception in this case we are going to pass a simple date format so for that I need a Java dot simple date format package I’ll import that now I’ll make the classes public and let’s
Write the code for the simple rate format I’m going to create a reference called SDF so I’m going to pass the input date that we enter so this is very simple I’ll tell you how if we enter the date and this format then it should print us
Valid input or else it should throw an exception let’s see how to do that so in the try block first I have read the input date and then output date I have created a reference for them and if there is any error in case of changing the date format or by converting the
Date formats then that exception will be handled in the cache block and next in the main method I have used a scanner class to read the format so let’s run the program and check the output so first let’s enter the date format which is invalid so I’ll give something
So it’s telling that some error has occurred while converting the date formats so it’s telling exception is here that is when we are trying to parse the exception and the unpassable date will be so answer now let’s execute it one more time and enter the proper date
Format that is 0 1 0 1 1 a 9 6 so it’s telling after changing the date format it will be this that is the one which I have given in this format from the input date format which is in day month and your it change the output date format by
Passing the input date to your month and day correct so this is how we can pass the exception so that brings us to the end of the session I hope you have understood the concepts of exception handling that’s all for today thank you and have a nice day
I hope you have enjoyed listening to this video please be kind enough to like it and you can comment any of your doubts and queries and we will reply them at the earliest do look out for more videos in our playlist and subscribe to any rekha channel to learn more happy learning
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Got a question on the topic? Please share it in the comment section below and our experts will answer it for you. For Java Training Curriculum, Visit our Website: http://bit.ly/32Ymvde
Good explanation👌
Where can we get the ppt
Very nice
thank u so much , tomorrow is my exam and i just finished this topic in less than an hour
thank you ma'am the explanation was exceptional
for what purpose exception object is given in catch blocks, is anywhere will be used?
good content with more clarity what is thought.thank u
can you provide code file handling use in GUI while making GUI application for bank
Thank you so much. Its very useful to all programmer
The video is very good and it has covered about all important concepts and parts. Thank you.
thank you!!!!
Super easy understanding
the teaching is fabulous ,i learned it in one shot
can we get full java explained in depth
explaining each point in a simple way
thanks .it was very useful
Fantastic 👍
Great Explanation!!👍👍
Great explanation mam, really explained very clearly
we can use finally without using try block?
This video is so awesome please can iget slides
really useful thank you!
Great explanation!Much appreciated.
Great explanation
Excellent explanation.🙏 Thanks.
Very well explained mam..
Awesome explanation on Exception Mam.
Well explained, thanks!
The way you teach that's very much easy to understand the concepts. 😃 #HatsOffToEdurekha🤝
This video has helped me a lot thank you !!
Quality Video. 🙂
Wonderful explanation mam👍☺️
Gem of a channel..
It is next level OSM explanation….Thank you so much
Great explanation thank you a ton!
Thank you so much❤️
excellent explanation, new favorite youTube channel, thank you so much!