Introduction to Exceptions:
- In the process of compilation and execution of Java application, chance of getting 3 types of errors (Syntax, Logical and Runtime).
- Exception is a Runtime Error.
- Exception is a class.
- Exception causes abnormal termination of program.
- Exception need to be handled.
Compile time errors: A syntactical error occurs when we violate programming language rules while writing programs.
class Check
{
static
{
static int a=10 ; //Error: local variable cannot be static
}
}
Some more examples:
- Every method should have return type
- Abstract and final cannot be combined.
- Class cannot be private.
Logical errors: The result is unexpected if the program is logically in correct. Compiler and JVM will not generate any error message in case of logical error.
class LogicalError
{
public static void main(String[] args)
{
int a=5 , b=2 ;
float c = a/b; (int / int = int)
float c = (float)a/b ; (float / int = float)
System.out.println("Result : "+c);
}
}
Runtime errors:
- It is called Exception.
- Violation of JVM rule gives Exception.
- A programmer need to analyze all the situations which can generate errors while application is running.
- Exception needs to be handled at runtime but logic must be implemented at compile time.
- Exception logic executes only when the problem has risen at runtime.
- Programmer need to define code for success and failure cases.
- Failure case always raises exception.
- Runtime error causes:
- Abnormal termination of program
- Informal information to End user.
import java.util.Scanner;
class ReadInt
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter ATM PIN : ");
int pin = scan.nextInt();
System.out.println("PIN is : " + pin);
}
}
Compile the code: