UNIT I_ Basic Syntactic Constructs in Java (2)
UNIT I_ Basic Syntactic Constructs in Java (2)
Exception Handling
Error
An Error is a serious or unavoidable mistake, these errors are
uncontrollable. Errors are usually caused by serious problems that are
outside the control of the program, such as running out of memory or a
system crash.
Type of Errors
1.Compile time Error:
a.The errors that are detected by the Java compiler during the
compile time are called the compile time errors.
b.When the compiler issues the errors it will not generate the
.class file. Hence we must eliminate all the compile time errors
first.
c.The most commonly occurring compile time errors are
1. Missing semicolons.
2. Wrong spelling of keywords and identifiers.
3. Missing brackets of classes and methods.
4. Missing double quotes in the string.
5. Use of undeclared variables.
6. Use of = instead of ==
7. Incompatible types in assignment statement.
8. Illegal reference to the object.
2.Runtime Error:
a.The runtime errors are basically the logical errors that get
caused due to the wrong logic.
b.The most commonly occurring run time errors are
1. Accessing the array element which is out of the index.
2. In an expression, divide by zero.
3. Trying to store a value into an array of incompatible types.
Exception
Exception Handling:
catch: Your code can catch this exception (using catch) and handle it
in some rational manner. System-generated exceptions are
automatically thrown by the Java runtime system.
A catch block immediately follows the try block. The catch block can
have one or more statements that are necessary to process the
exception.
Syntax: catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
throw: It is mainly used to throw an instance of user defined
exception.
Example: throw new myException(“Invalid number”);
assuming myException as a user defined exception
1. ArithmeticException
1.Occurs when an illegal arithmetic operation is performed.
2.Example: Dividing a number by zero.
Example Code:
int a = 10 / 0; // Will throw ArithmeticException
Common Message: / by zero
2. ArrayIndexOutOfBoundsException
1.Occurs when you try to access an array element with an index that is
outside the valid range (0 to array.length - 1).
Example Code:
int arr[] = {1, 2, 3};
System.out.println(arr[5]); // Invalid index
Common Message: Index 5 out of bounds for length 3
3. NullPointerException
1.Thrown when a program attempts to use an object reference that has
not been initialized (i.e., it points to null).
Example Code:
String str = null;
System.out.println(str.length()); // str is null
4. NumberFormatException
1.Occurs when a method attempts to convert a string into a numeric
type, but the string is not properly formatted.
Example Code:
String s = "abc";
int num = Integer.parseInt(s); // Invalid number format
5. ClassNotFoundException
1.Thrown when an application tries to load a class through its name but
the class cannot be found.
Example Code:
Class.forName("com.example.MyClass"); // If class does not
exist
6. IllegalArgumentException
1.Thrown to indicate that a method has been passed an illegal or
inappropriate argument.
Example Code:
Thread t = new Thread();
t.setPriority(100); // Priority must be between 1 and 10
7. IllegalStateException
Thrown when a method is invoked at an inappropriate time (i.e., the
environment or state of the application is not suitable for the
requested operation).
Example Code:
Scanner sc = new Scanner(System.in);
sc.close();
sc.nextLine(); // Scanner is already closed
8. NegativeArraySizeException
Occurs when an attempt is made to create an array with a negative
size.
Example Code:
int arr[] = new int[-5]; // Negative size
9. InputMismatchException
Thrown by Scanner methods when the input does not match the expected
type.
Example Code:
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); // Enter a non-integer value like "abc"
Steps:
Example:
class Test {
public static void main(String args[]) {
try {
int age = 15;
if (age < 18)
throw new MyException("Age less than 18");
System.out.println("Eligible");
} catch (MyException e) {
System.out.println("Caught: " + e);
}
}