EXCEPTIONS IN JAVA

EXCEPTION IN JAVA: When a program runs into an error (like dividing a number by zero, accessing an invalid array index, or trying to open a file that doesn’t exist), Java creates an exception object that describes the error. The program can then handle this exception to continue running instead of crashing.
They can be caught and handled
using try
, catch
, and finally
blocks.
BUILT-IN EXCEPTION: Built-in exceptions in Java are
the predefined exception classes provided by the Java API (in the java.lang
package and others). They represent the most common errors and abnormal
conditions that can occur during program execution.
·
They are automatically created and thrown by the Java Virtual Machine(JVM) when an error occurs. You can
handle them using try-catch.
EXAMPLE PROGRAM FOR BUILT IN EXCEPTIONS:
//
Demonstrating Built-in Exceptions in Java
public class BuiltInExceptionsDemo {
public
static void main(String[] args) {
// ArithmeticException
try {
int
x = 10 / 0;
} catch
(ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e);
}
// ArrayIndexOutOfBoundsException
try {
int
arr[] = {1, 2, 3};
System.out.println(arr[5]);
} catch
(ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e);
}
//NumberFormatException
try {
String s = "abc";
int
n = Integer.parseInt(s);
} catch
(NumberFormatException e) {
System.out.println("Caught NumberFormatException: " + e);
}
//
StringIndexOutOfBoundsException
try {
String s = "Hello";
char
c = s.charAt(10);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Caught StringIndexOutOfBoundsException: "
+ e);
}
//
NegativeArraySizeException
try {
int
arr[] = new int[-5];
} catch
(NegativeArraySizeException e) {
System.out.println("Caught NegativeArraySizeException: " + e);
}
System.out.println("\nProgram executed. Common built-in exceptions
handled.");
}
}
Output:
Caught ArithmeticException: java.lang.ArithmeticException:
/ by zero
Caught ArrayIndexOutOfBoundsException:
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
Caught NumberFormatException:
java.lang.NumberFormatException: For input string: "abc"
Caught StringIndexOutOfBoundsException:
java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 5
Caught NegativeArraySizeException:
java.lang.NegativeArraySizeException: -5
Program executed. Common built-in exceptions handled.
throws keyword: The throws
keyword in Java is
used to declare the exceptions that a method may throw, so that the calling
method or code is aware of and can handle those exceptions.
Multiple exceptions can be declared using a comma (,
) separator.
Example program for throws:
import java.io.*;
public class ThrowsExample {
// Declaring that this method may throw IOException
public static void readFile() throws IOException {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
System.out.println(br.readLine());
br.close();
}
public static void main(String[] args) {
try {
readFile(); // must be handled here
} catch (IOException e) {
System.out.println("Exception handled: " + e);
}
}
}
Output :
Exception handled: java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
throw
in Java-
The
throw
keyword is used to explicitly throw an exception (either built-in or user-defined). -
Only one exception can be thrown at a time.
-
It is usually used inside a method or block.
Syntax for throw: throw new ExceptionType("Error Message");
Example Program throw keyword used in Built-in:
import
java.util.*;
public class
UserDefinedException {
public
static void main(String[] args) {
int age=12;
try {
if(age<18){
throw new
InputMismatchException("Not eligible to vote"); }
} catch
(InputMismatchException e) {
System.out.println("Input
Exception: " + e.getMessage());
}
}
}
Output:
Input
Exception: Not eligible to vote
Example Program throw keyword used in User-defined:
class CustomException extends
Exception {
public CustomException(String
message) {
super(message);
}
}
public class UserDefinedException
{
public static void main(String[]
args) {
int age=17;
try {
if(age<18){
throw new
CustomException("Not eligible to vote"); }
} catch (CustomException e) {
System.out.println("
Exception: " + e.getMessage());
}}}
Output:
Exception: Not eligible to vote
ASSERT: The assert
keyword
in Java is not an exception-handling keyword like try
,
catch
,
or throw
.
Instead, it is a debugging aid that
helps programmers check assumptions during runtime.
What does assert
do?
·
It evaluates a boolean condition.
·
If the condition is true → program continues normally.
·
If the condition is false → JVM automatically throws an AssertionError
(which is an unchecked exception).
So, assert
indirectly works with
exceptions because it throws an AssertionError
when the condition fails.
Syntax:
assert
condition;
assert condition :
"Error Message";
Example program using assert keyword:
import java.util.Scanner;
public class Assert
{
public
static void main(String args[])
{
Scanner
sc=new Scanner(System.in);
try{
System.out.println("Enter sub1
marks:");
int sub1=sc.nextInt();
assert
sub1<=100:"Sub1 should not greater than 100";
System.out.println("Enter sub2 marks:");
int sub2=sc.nextInt();
assert sub2<=100:"Sub2 should not greater than 100";
System.out.println("Enter sub3 marks:");
int sub3=sc.nextInt();
assert sub3<=100:"Sub3 should not greater than 100";
double tot=sub1+sub2+sub3;
System.out.println("Total is:" +tot);
}
catch(AssertionError e)
{
System.out.println(e.getMessage());
}
} }
Output:
Enter sub1
marks:
100
Enter sub2
marks:
150
Sub2 should
not greater than 100
Comments
Post a Comment