Different kinds of exception
In this section, we will take a look at how we can handle exceptions in Java.
In general, if there is an error in the code, we need to catch it and print a message without failing; this can be done using the try...catch
mechanism. So in general, when we try to write code and we suspect that there might be an error in it, we will use that error for exception handling.
We'll explain it with the help of an exercise. Let's create a new class, exceptionDemo
, and inside the main
block we declare the a
, b
, and c
variables and assign values of 4
, 7
, and 0
, respectively, to them. We add a try
block inside the main block and we declare an integer variable, k
, which is equal to b
divided by c
. Whenever we add anything in the try
block, we are trying to see whether the code works. If it fails, the controller will come out of this try
block and enter into the catch
block that contains the exception. An important point to remember is that the catch
block comes right after the...