We know that there are various types of error which we might come across in coding, they are broadly classified as following types:
1. Syntax Error
Error in the syntax such as initializing value without declaration, absence of semicolon etc are considered syntax error.
2. Logical Error
When wrong logic is applied to the code, it is called logical error. This type of error do not cause any problem in compilation or execution but they perform the wrong task, i.e. the code doesn't behave in the expected manner.
3. Runtime Error
These are the errors that we do not realize until the code is run, i. e. we cannot view them at compile time as they occur at runtime. These errors can usually be treated and these are then called exceptions.
Exception:
So exception in java is basically a resolvable event the disrupts the normal flow of program.
common exceptions that we come across are:
- NullPointerException
- ArithmeticException
- ArrayIndexOutOfBoundException
- -IllegalArgumentException
- -NumberFormatException
Try catch and finally block:
So assume following code, in this I've declared an array, and its asking the user to enter an index to be retrived. As the length of array is 5 so entering index til 4 is valid and if index greater than 4 is entered in normal circumstances it would give error.
But we do not want our program to crash over such pity things such as invalid input so we perform exception handling, where we make two blocks a Try block that contains the code that might cause error, by this we tell the compiler to try doing that part of code, and if it throws an error it is given to the Catch block which catches the error by its type mentioned in the parentheses and then does the action that shows us that the error has been dealt.
And then we have Finally block that is executed whether any error arise or not, the only time it is not executed is when there's an error in the finally block as well, or when it contains a dead thread or when we use System.exit().
Top comments (0)