Exception Handling in JAVA 1
Exception Handling
Exception Handling is the mechanism to handle runtime errors. We need to handle such exceptions to prevent abrupt termination of program.
A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc
What is exception ??
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime
The code that's responsible for doing something about the exception is called an exception handler.
What is exception handling ??
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario.
statement 1;
statement 2;
statement 3; //exception occurs
statement 4;
statement 5;.
Suppose there is 5 statements in your program and there occurs an exception at statement 3, rest of the code will not be executed i.e. statement 4 and 5 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.
Exception class Hierarchy:
- All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy.
Throwable -> Exception -> RuntimeException
- Exception class is for exceptional conditions that program should catch. This class is extended to create user specific exception classes.
- RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs.
Exception are categorized into 3 category:
1) Checked Exception (Compile-time)
The exception that can be predicted by the programmer.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.
1. Using equals() method:
equals() method compares two strings for equality. Its general syntax is,
2) Unchecked Exception (Run-time)
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.
3) Error
Errors are typically ignored in code because you can rarely do anything about an error. Example : if stack overflow occurs, an error will arise. This type of error is not possible handle in code.
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )