Session 18 - Exception Handling in Java | Try..Catch..Finally Blocks

SDET- QA12,187 words

Full Transcript

so today uh we'll discuss one 

concept exception handling in Java okay so exception handling in Java 

so basically uh exception is event which will cause program termination so actually in 

the programming languages error is different exception is different Okay so both are not same 

so error means we have a syntax error we have a logical error but exception is not com this 

exception is totally different than error but here what is an exception exception is an event 

which will cause program termination which will cause program termination so when the program 

will be when the exception will come this is a user mistake basically so before understanding 

exception let us try to understand uh what is an error and how many types of errors are there 

so we have two kinds of Errors syntax errors and uh second thing is logical errors syntax 

errors logical error so what is syntax error suppose while writing your program if you miss 

some semicolon or if you miss some curly brace and if you use lowercase character instead 

of uppercase character they're all syntax errors that means if you're not following any 

Java syntax while writing your program it will give you syntax errors okay syntax error is a 

purely programming related errors if you're not following Java syntaxes properly you will get 

a syntax errors and we can easily notify them also so when you're writing a program in your 

egls it will clearly notify you with color red color line so they all comes under syntax errors 

programming mistakes second is logical error so logical error means the program will execute 

but output we are expecting is not correct if you have a syntax error in your program program 

will execute sorry program you cannot execute if you have a syntax errors in your program you 

cannot execute first of all but if you have a logical error in your program you can execute your 

program but the output or result is incorrect or inaccurate that's called logical error for example 

if you write a program for adding two numbers let us say you have provided two inputs that a two and 

five so what is an output You're Expecting is five but instead of five if you're getting minusy 

or something else that is a logical error so that is a major difference between syntax error 

and logical error so these two are related to programming errors purely developer mistakes at 

the time of developing or writing a program we do mistakes so syntax and logical errors comes under 

this category now what is an exception exception is not an error exception gives when you when the 

user provided some invalid input to the program it is totally user mistake syntax and logical 

errors comes because of development mistakes exception comes because of user mistakes okay 

for example let me explain what is uh exception here so normally when you write your program 

execution will happen top to bottom let's say I have written multiple programs like this 

okay so how execution will happen execution will happen line by line step by step execution 

will happen suppose somewhere in the program you have provided some input here some input value or 

you have assigned some value and if that input is not correct or if the input is not incorrect 

okay then what will happen is this input is using by some other statement right so that 

will throw the exception that will throw the exception when the input is invalid or input is 

incorrect then the statement which is using this input value will throw the exception because 

of this exception what happens rest of the lines will not executed rest of the code or 

rest of the program will not be executed so as soon as you get an exception the code will 

not be executed the program will immediately terminate or the program will be terminated by 

this exception so that exception will throw if your user is provided invalid input to the program 

or the user is provided some incorrect input or not appropriate input to the program then the 

statement will throw the exception what is the problem with the exception is the program will 

be terminated immediately second thing is rest of the statements will not be executed this is 

the problem with the exception now as a developer what we have to do is we have to identify where 

exactly the user is providing input okay and if the input is valid then anyway we'll continue the 

program without having an exception and suppose the input is invalid the statement will throw 

exception right so wherever the input is provided by the user we will identify those areas and we 

will put those statements as part of exceptions that means once the statement throw exception 

exception will throw that is sure whenever you pass input invalid exception will throw now 

we have to handle that exception go back and then execute the rest of the statement so this 

process is called exception handling process so whenever the statement throw exception we will 

handle that exception and get back and execute the rest of the code so whenever exception comes 

exception will terminate the program by default and it throws exception and as a development as 

per expect exception handling we have to handle that exception we have to find out which exception 

it will throw and uh we will handle it and go back and execute the rest of the code this is a process 

of exception handling okay so exception is what exception is an event which will cause program 

terminated it is purely user mistake and errors are development mistake developer mistake synx 

logical eror while writing the program they make some mistakes they comes under syntax errors 

and logical errors okay that that is a major difference between exception and errors right 

so now the concept is okay because of exception program is termin program is terminated 

immediately and then rest of the code is not executed but in exception handling process we 

have to handle that exception we have to go back and execute the rest of the code so we'll see how 

to handle the exception but first of all we will see how many types of exceptions are there okay 

and then when you will get an exceptions we'll see some examples and after that we'll see how 

to handle the exceptions okay now uh let me clear this fine now there are two kinds of exceptions 

in Java there are n number of exceptions we can categorize into mainly two categories types of 

exceptions uh one is checked exceptions the other one is unchecked exceptions checked exceptions 

unchecked exceptions checked exceptions are nothing but the exceptions which are identified 

by Java compiler so we no need to do more work on this because Java compiler itself will easily 

identify these type of exception it will just intimate you so where and all the chances are 

there to get an exception it is very easy to handle also so checked exceptions are exceptions 

which are identified by Java compiler interrupted exception file not found exception IO exception 

these are all different examples again every category there are n number hundreds and thousands 

of exception types are there in Java and uh but if you understand how to handle one type of exception 

you can easily handle any type of exception the way of handling the exception is exactly the same 

so the checked exceptions or exceptions which are identified by Java compiler and checked exceptions 

or exception which are not identified by Java compiler so we have to identify this so we need 

to work more on this unchecked exceptions because the Java compiler cannot identify so we have to 

identify these type of exceptions and we have to handle this examples arithmetic exception N Point 

exception array index out of bound exception so these are all different type of exceptions comes 

under unchecked exceptions so first of we will start with unchecked exceptions because here 

we have to do more work than checked exceptions checked exceptions are very easy to handle because 

Java compiler will easily identify them but unchecked exceptions we have to identify and uh 

we have to handle it okay so let me show you one example we'll start with unchecked exceptions 

okay now go to our project create new package say day 18 so new class and I'll name it as exceptions 

demo okay so we'll take main method and also take finish so just just notice here I'm trying to 

show you some types of exceptions and almost different exceptions will come in different 

aspects or different scenarios but we don't need to know each and every exception type and 

each and every scenario because there are so many hundreds and thousands of scenarios or there 

thousands of exceptions are there in Java so if you just learn two or three exceptions 

the same way we can handle any other type of exceptions okay so first we will see uh 

when you will get exception and if you get exception what is a problem with that so I'm 

writing a simple code here system print and here I'm writing simple statement program is 

started and uh after that I'm writing two more statements program is completed and exited 

so here I will write some piece of code and uh what I will do is I will take some input 

from the user okay some number I will ask from the user so how to take input from the 

console by using scanner class right I can take one scanner class scanner ESC is equal 

to new scanner and here I can say system do in can just import the scanner okay now let us 

uh take a number from the user so what I will do is I'll ask one input I say enter a number 

enter a number and once the user is provided a number we have to take into a variable so I'm 

creating one variable integer number equal to SC dot next in I'm taking one integer variable 

so after this is taking the input from the user so once you take the input from the user I will 

perform some operation by using this number so what I will do is I will perform 100 divided by 

this number whatever number the user is provided I'm dividing this 100 by this number so this 

is the operation I have done okay so this is a simple code I have written now execute this 

code run as Java application and it is asking for the program is started and enter the number 

now I'm passing some number let's say five I'm passing press enter so once you provided the 

enter five so it is saying you got a 20 is an output so this is written the proper output and 

program is completed then last statements rest of the statements are successfully executed okay 

so no problem in this everything is went smooth because we provided a valid user valid input to 

the program okay now one more time I'm executing so this time I will provide let's say zero by 

mistake I provider zero when I say enter now we can see an exception so exception in thread main 

so java. long arithmetic exception divided by zero so this is a exception name actually arithmetic 

exception every exception is a predefined class in Java so this is thrown Artic exception so when 

you will get this exception if any number divided by zero will throw arithmetic exception if any 

number divided by zero will throw arithmetic exception okay so what is a mistake here is user 

is provided invalid input user should not provide zero other than zero you can provide any other 

number because user is provided zero here when I using that input in this statement so this 

statement throw this exception that's the first thing second thing okay because this statement is 

thrown this exception these two statements are not executed that means the program is got terminated 

exactly in this line line number 15 the program is got terminated so rest of the statements are 

not executed so this is the problem of exception now my requirement is even though the statement 

is thrown exception still I want to execute the rest of the statements so how can we do this 

once you handle that exception it is possible so once you handle that exception then we can 

execute the rest of the statements and we can avoid termination of the program immediately so 

because of one statement how can I can stop rest of the statements I still want to continue with 

the rest of the statements okay I don't want to terminate the program immediately because of that 

exception so we have to handle that exception so that we can execute the rest of the statements 

and program will not be terminated so that's the main goal of exception handling okay this is one 

type of exception we have seen so what type of exception this is thrown arithmetic exception 

arithmetic exception okay this is example one and example one okay so let us comment this 

I'll show you some more how to handle exception I will show you in the next example so this is 

one example now let me show you another example example two so this time uh what I will do is 

I will create one array in a equal to new int of five okay so how much size it is five so 

total number of positions are allocated are five what is the starting index zero the last 

index four 0 to four is index values and five locations and five values I can assign into 

array so now what I will do is I will ask user to provide the value and also in which 

position I want to add that value so there are two values I want to ask from the user one 

is the the location where you want to add that number that is position and what value you want 

to add what is a value I want to add two values I will ask from the user okay so the first thing I 

will ask for the position system out. print enter position enter the position where exactly you 

want to insert the value in the array enter the position and uh what is the starting index here 

0 to four right between 0 to four we can give anything five is not allowed because index is 

last index is what four so between Zer to four you can provide any position so that position 

I will take as an input in P equal to dot next int so scanner class object I already created 

above so I'm using it so here in this statement I'm taking position in which position I want 

want to add value now also I will ask value which value I want to add in that position so 

system. out. println here I'm asking enter uh enter a value I'm also asking value value can 

be anything and also I'm taking that value in a variable in value equal to dot next in so I'm 

also taking value from the user also position now what I have to do is this particular value 

I want to insert in this position in the array because five positions are there so I'm asking 

position as well as value both so now we need to take this value and put inside this position 

so how can we do this a of a of position okay in which position a of 1 2 3 4 up to 0 to 4 

equal to the value so what the statement will do is whatever value we have added that value 

will be inserted in array in exactly in that position which we provided in this statement 

okay and after that I will print that value a of position in the same position whichever 

value we have added here I'm just trying to print the value here so this is simple go 

I have return okay let's try to execute now right so it is asking for the position 0 to 4 so 

0 to four we can give any number position because array size is five so let's say one I'm giving 

position is one and value also it is asking I'm say 100 okay now it is got printed 100 this is 

perfectly fine so program is completed program is got executed so everything executed fine okay 

now notice this so how many many positions are there only 0 to four 0 1 2 3 4 is allowed but now 

I what I'm doing I'm giving five here okay so do we have a fifth position in array in Array do we 

have a fifth position no so this is a user input right this is a invalid input it is not right 

input so when I guess enter it is asking for the value also let me give value called 100 now just 

observe it is trying to enter this value in the fifth position but in Array we do not have a fifth 

position so this will give you array index out of bonds exception AR a index out of bond exception 

means we are trying to insert a value out of bound so the maximum upper bound is what only four but 

we are trying to insert the value above the four so who mistake it is it is a user mistake we have 

provided five but actually 0 to four only we have to pass so this is again user mistake this will 

throw array index out of bound exception this is another type of exception this particular 

statement thrown array index out of bound exception okay so how to handle this I 

will show you in the next example first we will see different type of exceptions 

to understand better okay these are all unchecked exceptions because we have 

to identify them right so array index outut of B exception so now I'll show 

you one more type of exception example three okay I'm instead of taking input from 

the keyboard I'm directly providing input here string s equal to welcome this is also an input 

right but instead of taking from the user I'm directly keeping the input inside the program 

itself so this is also input okay now or else I can say 1 2 3 4 5 this is the input string now 

I want to convert this into number format I want to convert the string format to number format how 

can we convert string to number integer string to integer the last classes I think in the last class 

only we discussed yes we have to use wer class what is the target type is integer so we have 

to take integer wer class integer dot parent of yes so this will convert integer into string into 

integer that I can store in a variable so here I'm taking one more variable called number and after 

that I'm trying to print this number so what what exactly we have done is we have taken one input 

here string then we are trying to convert into number and after that we are printing the number 

so when I execute this this will work fine so same thing program is started 1 2 3 4 5 is taken as 

positive input and then executed fine instead of this number if you give alphabets can we convert 

this into number no we cannot convert so this will throw exception number format exception it will 

throw because this is also user mistake we have to pass only numbers in the double quotations then 

only we will able to convert into number if you pass alphabets we cannot convert into alphabet 

so here this statement is grown exception number format exception so what happens because of this 

exception rest of the statements are not executed and program is terminated immediately like this 

you can see so many types of exceptions while writing your programmer writing your automation 

scripts okay and we should able to handle so but how we can notice how we can identify particular 

statement is throwing some exception while writing the code how you will notice it simple thumb rule 

wherever the chance is there for providing input or wherever you're taking some input definitely 

there is a chance of getting an exception okay for example if you take these three examples in 

the first example where you are taking input here you're expecting the input so definitely there 

is a chance of getting some invalid input by the user and so we need to put this in the exceptions 

block so we need to handle here and if you take the example two I'm asking for the position also 

I'm asking for the value so definitely there is a chance of getting an exception because user may 

provide invalid input or invalid output invalid input somewhere so there is a chance of getting 

an exception and similarly if you just take a third example the third example also here there 

is a chance of providing some invalid input so definitely there is a exception okay there are so 

many number of exceptions are there like this and we can handle that exception in the similar Way 

by using right catch block null pointer exception also sometimes we will get let me take another 

example example four null pointer exception so null pointer exception you will get whenever 

you perform operations on null variables null is nothing but unknown value it is not empty it 

is not zero null is nothing but unknown okay for example I'm taking one string variable string 

s equal to null or I can say string s equal to welcome I'm taking one input here okay when I take 

string variable I can apply all kinds of string related methods right so what I will do is I'll 

try to find length of a string s do length Okay and here you can s do length I'm trying to print 

so I have taken one string as an input and then I'm trying to find length of a string so this will 

give you length of a string seven perfectly fine suppose if you don't have this string okay suppose 

I don't have value in this okay this is empty this is not unknown actually this is empty so this will 

obviously return zero because there is no number of characters in a string obviously returns zero 

okay but if you say null here null null is nothing but unknown value okay and when you perform 

operation on the null variables you will get a null pointer exception when I execute as a Java 

application now we can see null pointer exception not only strings you can uh add this null for 

any type of variables and when you perform operations on those type of variables you will 

get null pointer exception because if you don't know the value first of all value itself is not 

there for this variable how can we operate that variable without having that value right so that 

is the reason it is giving null pointer exception so this statement will throw null pointer 

exception actually not this one this one will throw null pointer exception okay so these are all 

different type of exceptions you may see while you are writing a program okay now the second step is 

okay we understood the problem with the exceptions we understood two things actually when you will 

get an exception and the second thing is if you get an exception what is a problem so these are 

the two things we have notified so whenever you pass invalid input to the program you will have 

a chance of getting an exception that's the first thing second thing once you get an exception the 

program is terminating that is the second thing so now we cannot control the input because user can 

provide anything right we cannot say we can just intimate the user so provide the valid username 

or valid password but user may provide invalid also chances are there we cannot have any control 

on that but once you provided user invalid input we have to identify that accordingly we have to 

handle the exception I will give you simple real time scenario where exactly these exceptions are 

used simple example with this we can understand very easily okay so let us take uh a simple login 

scenario any application will start with the login screen right so let's say you have a login screen 

in this we have to provide username we have to provide your password so user and password then 

we click on okay button then it will go to the homepage okay this is a screen actually UI the 

back end how exactly it will work I will show you so as a user what I'll do is I will provide 

username and password once you provided username the username and password will be taken by 

the program and verify that user password is correct and after verification it will allow us 

to login the program will do that okay suppose if the user is provided invalid username or invalid 

password or blank username blank password that also we will capture at the time of verification 

we will notify the input is not correct then what will happen immediately the application is not 

crashing right when you provide username and valid invalid username password what will happen 

normally it will give you intimation right invalid user name invalid password you will get some user 

message user understandable format message but your application is not crashing your application 

still alive your application still working but it is just intimating you provided some invalid 

data so in exception handling works like that so whenever you take input from the user validate the 

data is correct if the data is not correct then we will handle that and tell the user back you 

have provided invalid input so please correct it and because of this is called exception handling 

because of this what happened application will not crash and user will able to provide another input 

okay so this is a simple example for exception handling how internally the developers will write 

the code so here there is a chance of getting invalid input by the user this we don't have 

any control user can provide any type of input we don't have control but as a developer once 

you get an input if it is a invalid data instead of terminating the program and crashing that 

application we will just handle that exception and provide message to the user like provide valid 

data like that so this is example of exception hand okay now we will see some examp examples 

of uh exception how to handle the exceptions so we have seen some examples here now we'll see how 

to handle the exception and it can be any type of exception the handling mechanism is same so if you 

know how to handle one type of exception you can know you can handle any type of other exceptions 

so we don't need to know we don't need to discuss how to handle each type of exception because 

it is exactly the same how we can handle one type of exception in the similar fashion we 

can also hand all other types of exceptions okay now let us go and see one more example how 

to handle the exceptions so we understood two things so far one is when user provided invalid 

input there is a chance of getting an exception once exception is occurred then program will be 

terminated and rest of the code is not executed so these things we have understood so far now the 

next step is suppose if you get an exception how to handle it how can we avoid program termination 

so let's create a new class and I'll name it as handle exceptions handle exception taking main method okay now go back to the 

previous one I'm just copying one part let us say this part okay 

you can take any type of exception I'm taking the first example so here 

this is a code also I copy these two statements okay just observe so this is a code 

which we have return if I execute this code and it will ask for the number and if the number is 

invalid so I'm passing zero invalid number so this will throw the athematic exception now 

the thing is we need to handle that so here there is a chance of getting an invalid input 

right where is a chance here and this will also work fine the statement will not throw but the 

next statement wherever we are using this input for operation there exactly the exception comes 

so now we know exactly this is a place the user is providing input so maybe this statement May 

through exception if the user is provided invalid input here so we have notified that so once you 

notice this how to handle that exception is the next step so to handle that exceptions we have 

try and catch block so whichever statement is throwing exception we keep that statement in the 

tri block so inside this we can keep the statement whichever statement is throwing exception the 

statement we have to put in the tri block and after closing the try block immediately we have 

to start another block called catch block inside the catch Block in the catch we have to put the 

exception name in this bracket so what type of exception this statement is thrown that exception 

class name you have to specify for example if the statement is throwing arithmetic exception now now 

in the cat we have to write arithmetic exception like this arithmetic exception is a class so we 

need to provide some object reference variable also so this we have to mention and inside the 

catch block you can do whatever you want suppose if the statement throw exception and catch block 

will handle it so inside the catch block what I will tell I will provide the message to the user 

system system. pinell and here I can put can print exception statement exception message I can print 

in the console window or you can provide some information to the user like you provided some 

invalid input like that so in the catch block also we can write whatever statements we want so by 

using TR catch block we can handle exceptions so let me show you how to handle now which statement 

is throwing exception this particular statement is throwing an exception so I will put this statement 

in the Trib block like this and close this okay okay suppose if you have a confusion whether 

this statement is throwing exception or these statements are throwing exception if you have 

a confusion you can keep all three statements in one Tri block you can also keep all three 

statements in Tri block no problem because Tri block is allowed one or multiple statements if 

you don't know exactly which statement is throwing exception you can put group of statements directly 

in the tri block okay but here I know exactly this particular statement is throwing exceptions so 

that I can put only that statement in the tri block and immediately Tri block followed by 

catch block and catch block we should have a bracket here we need to specify exception type 

what is an exception that statement will throw arithmetic exception suppose if you don't know 

what exception it will throw there is another way to handle okay I will show you that so for now 

just assume this particular statement will throw arithmetic exception that we already know so that 

is the reason I'm putting arithmetic exception and give some variable object name and here if 

you want to print the arth exception exception details in the console window you can put or else 

you can write a simple message for the user like invalid data like this after that rest of the code 

will be continued so whichever statement is thrown exception keep that in the tri block and to handle 

this exception catch block should be there so who is handling that exception exactly try block or 

catch block catch block is catching that exception and this message will be given to the user and 

rest of the code will be as usual executes okay now let us execute so this TR okay if exception 

comes then only the catch block will execute if this the statement is not thrown any exception 

if you provide valid data right so then also the statement will execute if you provide valid data 

also the statement will execute but there is no exception so catch block will skip automatically 

catch block will not execute when the cat block will execute if the statement thrown an exception 

then catch block will be executed okay so let me show you both the scenarios when I run the 

Java application so now this time I'm passing valid data so successfully executed no problem 

now when I execute a Java application now I'm passing invalid data now observe we haven't get 

any exception in the console window earlier we got arithmetic exception but this time we haven't 

get any exception instead the catch block is got executed in the catch block the statement is got 

executed and rest of the code also successfully executed okay so this is the main ADV advantage 

of handling exceptions we can avoid program termination at the same time we can also execute 

rest of the code by handling exception so this is the only way we can handle exceptions by using 

try and catch block okay and one more thing suppose here we specify the arithmetic exception 

so this catch block will handle only if it is an arithmetic exception because if this statement 

is through some other type of exception or null poter exception or index outout exception in 

those cases this catch block will not handle because we specify arthamatic exception here so 

if the statement throw null pointer exception here it should be null pointer exception if 

the statement thrown array index Auto bound exception here we should specify array index Auto 

bound exception so then only the catch block will able to handle otherwise not okay so this is a 

simple examp example for handling the exception so to handle the exception what we have to do 

first we have to identify the statements where exactly there is a chance of providing input from 

the user and immediately where exactly that value you're using this value we are using in this 

statement so definitely there is a chance of providing a invalid input here so we have to keep 

this in the tri block and immediately catch block will handle it just hold on I will come to that 

part still we haven't completed the concept okay so this is the first example very simple way we 

can handle arithmetic exam arithmetic exception we have handle okay suppose you have identified 

some statements which will throw some exception but you don't know what type of exception it 

will throw okay you don't know what type of exception what what I'm saying here is whatever 

exception the statement throw the same type of exception name you have to specify in the catch 

block otherwise it cannot handle but suppose if you do not know what type of exception the 

statement will throw then how can we handle if you don't know which type of exception it 

is thrown in that case what type of exception we specify here right so here there are two 

approaches there are two approaches if you don't know what type of exception that statement 

will throw still we can handle in two different approaches okay one approach is we can write 

multiple catch blocks okay one dry block can have n number of catch blocks remember this one 

dry block can have n number of catch blocks after this catch I can write another catch block so 

in every catch block you can write a different type of exceptions and whichever exception is 

matching that particular catch block will be executed that is one approach but there is a 

problem in that approach I will tell you how to overcome that problem first of all let me tell 

you one example take a new class multiple catch blocks okay multiple hatch blocks one 

single Tri block can have multiple catch blocks okay so now let me show you how to write 

multiple catch blocks so what I will do is I will write uh simple code which will throw 

the exception let's say this is my code I'm taking string values null and after that I will 

perform some operation on null I can just find s. length so this will give you n null pointer 

exception right so when you print this so this will obviously gives null pointer exception 

but now I want to handle this now I want to handle this I can simply say program is finished 

okay so when you run this when you provide null here it is simply giving null pointer exception 

so now we need to handle so this statement is not giving exception this statement is giving 

exception because here it is taking input and here we are using that input so this statement 

is throwing an exception null pointer exception okay so now what I will do is I will keep the 

statement in the R Block so I can just put R Block but suppose you don't know what type of 

exception the statement will throw okay then what we can do we can write and multiple catch 

blocks so in the first cat block you can write arithmetic exception variable this one catch block 

and another catch block catch and here you can specify nullo exception and variable and even if 

it is not there you can write another catch blog another catch blog here you can say number format 

exception e so like this you can write multiple catch blocks and here you can provide a message 

or if you want to print what type of exception the statement will throw you can still print 

the type of exception simply what you can do is you can just print system do print uh there is a 

variable called e right arthamatic exception so e dot that is an object reference variable actually 

so there is a method predefined method called get message so this will give you the exception 

message and after that you can write simple statement to the user so user can provide here 

I'm just saying handle uh exception or handled exception right so I can put this in every catch block so if you do not know exactly uh what type 

of exception this statement will throw then you can still handle this by writing multi multiple 

catch blocks but at a time only one catch block will be executed if the statement through 

anthetic exception then First Catch block will handle and rest two will ignore and if the 

statement is through null pointer exception then this catch block will execute the first one and 

third one will ignore and if the statement is through number format exception then third catch 

block will execute first two catch box will ignore okay that's how it will work okay now currently we 

are throwing and if the statement is not throwing any exception then all catch blocks will be 

ignored okay now this statement is throwing null pointer exception so obviously the second 

catch block should handle this okay when I run this Java application now observe handle 

exception and which type of exception this is cannot invoke string. L because s is null it 

is clearly giving the message why the exception comes right this message e do get message this 

method is provided detailed information about the exception and finally program finished so 

rest of the statements are got executed even though we got an exception so this is how we 

can also write multiple catch blocks for one type of Tri block one try can have n number of 

catch blocks but there is a problem in this can anyone notice what is the limitation in 

this approach what is the limitation so if the statement is thrown an exception one 

of the catch block will handle that you can write multiple catch blocks with different type 

of exceptions okay there is a problem in this approach yes suppose this statement is thrown 

any other type of exception other than these three because in Java there are 100 thousands 

of exception types there so you mentioned only three types whatever the exceptions you 

know you mentioned only those three types but if the statements thrown other than these 

three exception anything else some other type of exception then still you have a chance of 

getting an exception that is the limitation and the second thing is your code is increasing 

right how many catch blocks you will write like this if you write so many cat blocks obviously the 

code will be increased and necessarily right so that is another problem but how can we solve this 

problem if you don't know the exception still you can solve the problem just by writing one catch 

block with one catch block can handle this how can we handle this instead of writing multiple 

catch blocks can just write only one catch block okay one catch block and normally what you will do 

here you'll specify the exception type whichever exception the statement with thr that exception 

type is specify like Artic exception null Point exception number of and so on but here you just 

write Only Exception that's it exception e and this will handle all kinds of exceptions this 

catch block will handle all kinds of exceptions and you no need to write multiple catch blocks 

you can just comment them multiple catch blocks are not needed just one single catch block you can 

handle all types of exceptions how it is possible because exception is a parent class of all other 

exception classes this is a super class exception is a super class all other number format exception 

null pointer exception all these exceptions classes are derived from one super class which is 

exception so that is the reason exception class will handle all kinds of exceptions all kinds 

of exceptions so if you do not know what type of exception you will get simply you can write 

one single cat blog and specify the exception that's it okay now execute this will also handle 

any type of except arithmetic exception number form whichever exception you have here this 

catch block one single catch block will handle this okay so understood everyone so far what is 

an exception what is a problem with exception how to handle the exception okay and how to use 

try and catch block how to use try and multiple catch blocks now let me show you something 

else try and catch block we use to handle the exceptions any type of exceptions we have to 

use same kind of a block try and catch block and there is another additional block is also 

there that is optional if you want to use you can use it or else you can ignore it that is 

finally block get message exception this get message will get the information why exception 

occurred okay so if you run this code that e do get message is giving this statement 

this statement is given by this message get message this one what it is saying cannot 

invoke string. length because s is null it's very clear right because of s is null we cannot 

apply any methods because s is null there is no value in it but still we are trying to apply the 

method that's the reason exception comes so the same reason it is giving here the get message 

is part of this exception classes get message is available in this classes and we can access it 

by using this object variable e. get message like that okay it is not exception this is just a 

method and which will print the details of the exception this is a message for every type 

of different type of exceptions you will get a different type of message because the same 

exception will not match with other type of operation right yeah now in the TR catch Block 

in addition we have another block called finally block so first we will write Tri block and 

whichever statement is throwing exception we can keep those statements or statement 

immediately we will write one or more catch blocks after that we can write finally block 

finally only one catch block is having this bracket because we have to specify what type of 

exception it should catch and finally block is always followed by catch block even if you have 

a multiple catch blocks after completion of all the catch blocks you can write finally block 

okay so what is the use of finally block so whichever statement is throwing exception that 

we will keep inside the T block and to handle the exception we will keep the catch block but 

why do we need finally block okay so why do we need finally block so finally block statements 

will always execute whether you get an exception or you may not get exception in all the cases 

finally block will always execute okay suppose if the statements are executed catch block is 

handled exception and final block will execute the statements are executed but there is 

no exception catch block will ignore but still finally block will execute there are 

multiple cases are there all cases finally block will execute in every case finally block 

will execute okay let me write all the cases here case one suppose exception is occurred 

catch block will handled still finally block will execute exception is occurred catch block 

is not handled for example exception is occurred but catch block is not able to handle still 

final block will execute exception doesn't occur obviously what happens catch block will not 

execute but still finally block will execute means what finally block will always execute without 

depends on exception or exception comes or exception not com doesn't matter finally block 

is always execute okay but why we need to use finally block this is the optional block that's 

the reason they have not make it as a mandatory when you write a catch block when you write a try 

block catch is mandatory block but finally is an optional block if you want to write you can write 

otherwise you can ignore but what we can write finally block normally so if you want to execute 

any statements without depending on exceptions you can keep those statements in the final blog 

okay suppose I want to execute suppose normally what happens is in the real scenario I'll tell 

you uh when you're working with the databases especially or when you're working with the files 

or when you're working with the databases normally what happens is we will create three blocks Tri 

block catch block BL and then finally block just a second okay so normally when you're working 

with the file Concepts or when you're working with the databases we will write Tri block and 

immediately we will write catch block and finally and and finally block so in the tri block we will 

write the piece of code which will establish the connection or open the file suppose I have some 

text file okay I want to read this data from the text file so before reading this first our 

program should establish the connection to the file and open the connection we have to open 

the file right to read the data so for that we have to write some piece of code so that we will 

keep in the tri block okay suppose when you open the file or when you're trying to the connect 

to the file and when you're trying to open the file file doesn't have any data or file itself 

is not found in that particular location still there is a chance of getting an exception or not 

right file not found exception you will get so that exception will be handled by the catch block 

so this block will handle that exception handle exception okay but in the finally block what you 

will write if in the tri block we open the file successfully right then what we need to do after 

doing the operations on the file once your job is done then we have to close the file we have to 

close the connection so such type of code we will write in the finally so closing connections okay 

and closing the files so these type of code we will write in the final block this is the real Val 

okay so Tri block we will keep all the statements whichever can throw the exceptions yes you are 

right okay and in the catch block we will write uh which will basically handle that exception and 

if finally block we'll always use for opening and closing the connections of the files or database 

or whatever that's the purpose of finally block okay okay and if you're not opening any file or 

if you're not opening any connections in the tri block you no need to go with the finally block 

you can simply write TR catch block okay this is the use case I'm just example I'm going to tell 

you but it is always optional and it it doesn't depend on anything whether the exception comes 

or exception not come or exception handle or exception not handle it doesn't consider all 

those things all the statements in the final block will always execute that's how they 

have designed okay let's see uh one more example for finally block and also I told you 

three different cases right exceptions occurred catch block handle final block will execute same 

thing final block will execute in every situation exception occurred or not occurred handle or not 

handle doesn't matter finally block will always execute right so let's create another example 

uh with finally block try catch a along with finally block and in case if you have a multiple 

catch blocks where you have to put finally block after completion of all catch blocks at the 

end you have to add finally block okay now find block okay so now I'm just uh showing 

one example for finally block I'll copy this okay so let me copy the same code and then 

I will show you how to work with the finally block so this is your catch 

block this is another statement where is the tri block this is a tri block okay so now let us look at this example 

so here I'm taking SN this will throw exception and catch block so additionally I will put 

one more finally Block in the finally block you can write whatever you want so I'm just 

writing simple you entered into finally block I'm just writing a simple message okay so here 

I'm writing more meaningful message I can say when the cat block will execute if any exception 

comes catch block will execute so here I say catch block handle catch block handle exception 

okay now just observe this my first case this exception uh I'll put one valid data so 

in that case the statement will not throw any exception right the first case exception 

occurred catch block handle we'll see that exception occurred means if you have a 

null so exception will occur and catch block will handle so here I will put 

uh null pointer exception because when you put exception every exception will 

handle so here I'm saying null pointer exception okay so now this statement will throw exception catch block will hand 

handle after that finally block will execute okay just observe catch block is 

executed why because that statement is through an exception this is exception message 

and you enter into the finally block you can see the statement is executed from the finally 

block so entered into the finally block after that program finish it is executed okay 

so like this we can use finally block so this is one case exception is occurred handled 

finally block is executed first case now the second case exception occurred but catch block 

is not handled still finally block will execute so exception is occurred but when this catch 

block cannot handle if it is another type of exception let's say I'm saying number format 

exception number format exception now will it handle that exception no catch block block cannot 

handle that exception but still finally block will execute see here try block this statement throw 

exception exception is thrown cat block is not handled so exception message is got but still 

finally block is got executed see finally block is got executed and rest of the statement is 

got scaped because when the exception comes rest of the code will not be executed right but 

finally block will always execute even though the exception is occurred finally block will execute 

this is the second case suppose exception doesn't occur catch block will obviously ignore in that 

case also finally will execute for example here I have taken welcome so this will not throw any 

exception so here I can say again null pointer exception so this statement uh will not throw any exception obviously catch block will 

ignore but still finally block will execute okay so entered into the finally block 

program got finished so finally block is optional block and this block will always execute whether 

you get an exception or not getting an exception whether it's handled exception or not handle 

exception doesn't matter a finally block will always execute this is additional block which 

we can write after try and catch optional block means even though if you're not keeping this 

final block you can still use only try catch block but catch is mandatory block when you write 

a try we have to continue with the catch Block in between these two we should not write anything 

else after closing triy block immediately you have to start with the catch block after that 

finally block you have to write if you have a multiple catch blocks after completion of all 

the catch blocks then we have to write a final block but we should not not write final Block in 

the middle of this finally block always comes at the end of the catch blocks okay so these are all 

about unchecked exceptions what are exceptions so far we are discussed about our unchecked 

exceptions means we have to identify the scenarios and where exactly the user is providing 

invalid data and accordingly we have to keep those statements in the tri catch blocks and we have to 

handle the exceptions this is our developer job now we'll discuss about checked exceptions checked 

exceptions are very very simple but before going to checked exceptions is it clear everyone's 

unchecked exceptions unchecked exceptions are exceptions which are not identified by Java 

compiler so we have to identify and we have to write TR catch block and we have to handle 

it such type of exceptions are called unchecked exceptions exception type can be anything but the 

handle exception is the same way by using track C block okay now checked exceptions and very we 

will get very frequently checked exceptions while writing our automation code whenever 

you're trying to use some external classes very frequently we will get checked exceptions 

because we don't need to bother about this because Java will intimate you we can EAS easily handle 

checked exceptions like interrupted exception file not found exception IO exception these are 

all different examples of checked exceptions and simply I'll show you one example and anyway 

coming sessions we will see so many types of checked exceptions wherever it is getting checked 

exceptions we will able to handle it but checked exceptions we can handle in two different ways we 

can use TR catch block also we have to use throw keyword there is one more keyword is there 

called thros okay thros by using this throw keyword we can handle so checked exceptions can be handled in two ways so one 

is using using try and block try catch that is common and the other one is additionally throw 

keyword but most of the times we use throws keyword okay I will tell you why so first let 

me show you one example for checked exceptions how Java compiler will identify that exception 

see this uh I'm closing this uh I'm creating new class okay this is checked exception s okay so in this I'm just 

writing simple code just observe okay program started program is 

in progress and after that I will write two more statements so four statements have 

written so when I execute this code all four statements will execute at time one by one if 

I look at here immediately we got an output so what I want to do is once I print these two 

messages after that I will pass my code for some time here few seconds after that I want 

to execute these two statements okay once I executed first two statements I will pass my 

code or I wait for something and after that after 5 seconds or 10 seconds I will execute 

the rest of the statements for that in Java we have a method built-in method which is there 

thread is a predefined class in which we have a method called Sleep thread do sleep in this we 

can specify the time how much time you want to wait here how much time you want to pass your 

code let's say 5 seconds I want to pass means 5 milliseconds you have to provide so this will 

take time in milliseconds so 5 milliseconds equal to 5 seconds so I put this method so if you 

look at here right so thread do sleep so this sleep is a method which is already there in the 

thread and we are passing some data in this so This method will wait here five seconds after 

that rest of the statements will be executed but now if you look at this this statement is 

giving some kind of an error see it is not an error actually so the Java you can see this lines 

red color lines in two different scenarios one is if it is an error if you miss semicolon or if 

you use lowercase character inste of uppercase or if you miss curly bra in such case you will 

see this kind of a cross mark error underline in another is suppose your code is perfectly written 

and some statement will throw some exception that is already identified by Java so in those cases 

also it will give you error like this so when you put like this cursor it is saying unhandled 

exception type interrupted exception unhandled exception type interrupted exception so this 

particular statement will throw interrupted exception so Java is intimating us this but 

statement will throw interrupted exception so Java is intimating us so now what we need to do 

we have to handle this to handle this what we can do we can simply put this this in the dry block 

like this and immediately we can write catch block and what type of exception it will do interrupted 

exception that you can write interrupted exception e think this is a spelling mistake so interrupted exception 

this will throw can just put the cursor you will know exactly what type of 

exception will throw so this is the type of exception so you can keep in the tri block 

and here you don't need to remember the name of the exception also it will clearly show you 

so in the catch block you can write interrupted exception e and whatever you want you can keep 

in this bracket okay you can put like this or you can put in the same line if you don't want to 

write anything can just keep empty no problem okay this is how we can handle the check Exception by 

using Tri as usual so now I'm executing my code just observe first two statements are executed 

after 5 seconds then another two statements are executed so this particular statement will throw 

interrupted exception so Java is already notified that so it is intimating yes so better to handle 

this exception but what is interrupted exception so this particular statement only throwing 

interruptor exception so when you'll get this is uh let me tell you a scenario actually this 

is related to memory management uh multithreading concept but let me give you very high level 

overview what is interrupted exception see what exactly this statement will do is thread do 

sleep so whenever you start running your program for example you run your program so once you run 

your program uh some process will be created in the memory okay suppose if you have executed five 

programs five different processes will run parall and similarly if you run one program one process 

will run so as soon as you executed your program one process will be created processing in the 

memory there will be some memory allocated and in that memory the process keeps running once the 

process is completed then program will be exited automatically so what this thread do sleeve 

will do is as soon as you run your program the program is running that means the process 

is running and what exactly we are doing here we are saying thread do sleep means this command 

will make this process sleep for some time okay so five seconds we put so 5 Seconds this first 

two statements will execute after that 5 Seconds it will pause after that it will resume and 

then ex execution will start and finally exit so while this process is going on suppose if 

any other program is running parall any other program is running parallely that will also 

create another process right and this process May interrupt this particular process if you do 

not have enough memory okay if you do not have enough memory suppose there's some only same 

memory location this process is running here and immediately parall you run another program 

but how from where this process from where this program will get process memory again it should 

allocate here itself then normally what happens this is replaced by this so once one process 

is running another process May interrupt the existing process so there is a chance of getting 

an exception so that is the reason when I use this statement thir do sleep Java is intimating there 

is a chance of getting an exception interrupted exception so better to handle this when you put 

right catch block what happens even though some other processes interrupted this still we will 

not get an exception we will get exception but we will able to handle that exception so that is 

the meaning of this okay so we'll see other type of exceptions like file not found exception 

IO exception so many types of exceptions are there like this so in the coming sessions 

we will see so many exceptions but now just understand only this much so these exceptions 

are already identified by Java itself so we no need to bother how the Java is identified all 

those things so that is Java mechanism okay similarly there are so many types of exception 

for example uh here I'm writing some different code if you're not understood don't worry I'm just 

giving simple example let's say file input stream I'm using equal to new file input to stream 

okay and C drive somewhere I'm using text.txt right so I have written this statement so the 

file input stream file input stream s is a capital okay I'm just trying to import this okay now just 

observe this statement when you write what is the purpose of the statement is normally if you have 

any text file in your machion or Excel file or whatever file you have before reading the file 

you have to open the file in the reading mode so this statement will basically open the file 

in the reading mode later we will use this uh for reading purpose or writing purpose so this 

is a object actually file is representing the file object so we are opening the file and that 

is represented with this file so once you open the file we can perform some operations of the 

file so when you put this uh when you see this statement this is external class so we have to 

import this but after that it is still giving some kind of error if I put the cursor here 

what it is saying unhandled exception type file not found exception Java is intimating us 

you may get file not F exception error file not found exception in the runtime you may get file 

not F exception Java is identified this Java is intimating us but what is file not F exception 

you are executing the statement perfectly fine but at the time of executing the statement if the 

file is not available in that location right if the file is not available in that location is 

there any chance of getting an exception or not yes so that is the reason Java is intimating us 

before itself maybe file is there no problem file if is not there you you may get some exception 

so please handle this so that's how Java will identify so immediately what you can do we can 

put the statement in the try catch block okay so this is simple example I'm telling you if you 

not understood the statement no problem I can leave so how checked exceptions work how Java 

will intimate you so that's what I'm explaining here so as I told you checked exceptions we 

can handle two different ways one is trike catch block we already know and another one is by 

using throw keyword we can handle so let me show you how to handle by using throw keyw is very 

very easy and most of the times we prefer that also instead of TR catch block we prefer always 

throw keyword let me comment this TR catch block okay also comment this just observe I'm writing 

again thread do sleeper and 5 Seconds so this will throw unchecked exceptions or it will throw 

checked exceptions now without using Tri catch block how can we handle it put the cursor simply 

here it will show you two suggestions if you click on surround with the TR catch directly this 

will be added in the tri catch block this is the one one approach strike C block suppose if 

you have like this thread dot sleeper and if you want to add throws keyboard you can just put the 

cursor and select the first one here add throws declaration once you click on it just observe what 

will happen yeah for the method level there is one keyword automatically added throw and name of 

the exception so this is another way so at the method level we can specify the exception throws 

interrupted exception so this statement will throw interrupted exception so that is added here so 

this will also solve the problem so when you run this first two statements will execute then thread 

dot will wait for 5 seconds after that rest of the code will be executed by using throws keyword we 

can handle suppose I have another statement in the program that also will throw another type of 

checked exception then how can we add here so if you put the cursor it will show you add throws 

declaration right just click on it see another type of exception is got added so like this if 

you have n number of statements no problem each statement is throwing different type of exception 

still no problem you can all you can add all types of exceptions at the method level by using 

throws keyword throws interrupted exception file not found exception like this you can keep adding 

more number of exceptions okay by using TR catch block we can add exception we can handle checked 

exception also by using throw keyword we can handle Checker exceptions okay and TR catch block 

is statement level so whichever statement are throwing exception we will keep those statement 

or statements in the tri block it is statement level throw keyword we will apply at method level 

so in that particular method whichever statement is throwing exception that exception we will 

add to the method corresponding method by using throw keyword okay so what are the differences 

between checked exceptions or unchecked exceptions inter question what is the difference between 

checked exceptions or unchecked exception first difference checked exceptions are identified 

by Java compiler whereas unchecked exceptions are not not identified by Java compiler 

second difference checked exceptions can handle by using only Tri catch block sorry 

unchecked exceptions we can handle only with tri catch block checked exceptions we 

can handle by using TR catch block as well as by using throw keyword and another 

difference try catch block is statement level throws keyword is a method level okay 

so these are the differences you can just remember yes just adding the M uh exception 

to the main method it applies to all through the program yes so suppose if you write 

another thread do sleep okay same exception will applicable same interupt exception 

is applicable for all the statements okay only one time we will add that is only 

if you have one statement one statement is applic you have a multiple statement 

multiple statements you have only one keyword yes for checked exceptions also you 

can use exception class no problem okay so for example uh uh this particular statement 

is throwing some exception checked exception okay and uh then in the tri catch block you can 

specify exception here you can also specify the exception class okay but it's not recommended 

TR catch block first of all because as soon as you put the cursor here it will clearly show 

you what type of exception it will throw just click on ADD throws declaration link that will 

automatically add to the method so this is the simplest process for handling checked exceptions 

most of the times we follow this approach only for unchecked exceptions we have to take care our 

own self but right first identification is one thing once you identified then we can put them in 

the TR catch block if it is unchecked exceptions we have to take care of if it is checked 

exceptions we can simply add this declaration because Java itself is clearly giving you the 

notifications it is more simpler than uh checked exceptions okay clear everyone so this is all 

about exception handling concept so this much is enough once you start automation you will 

see so many types of exception in automation specific selenium specific there are some more 

exceptions are there element not F exception element interactable except not interactable 

exception stale element exception so because they are purely related to automation type 

exceptions again same way handling the exceptions are exactly the similar by using tratch blog and 

if it is a checked exceptions we can use throw keyword okay so uh let us stop here 

just practice these concepts for today and tomorrow we'll continue 

so this is all about exception handling okay so we'll stop here for today's 

session and uh we'll continue tomorrow

Need a transcript for another video?

Get free YouTube transcripts with timestamps, translation, and download options.

Transcript content is sourced from YouTube's auto-generated captions or AI transcription. All video content belongs to the original creators. Terms of Service · DMCA Contact

Session 18 - Exception Handling in Java | Try..Catch..Fin...