0% found this document useful (0 votes)
3 views

UNIT I_ Basic Syntactic Constructs in Java (2)

The document provides an overview of exception handling in Java, detailing types of errors (compile-time and runtime) and exceptions (checked and unchecked). It explains the mechanisms for handling exceptions, including try-catch blocks, finally blocks, and custom exceptions, along with examples of built-in exceptions. Additionally, it describes how to create user-defined exceptions by extending the Exception class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

UNIT I_ Basic Syntactic Constructs in Java (2)

The document provides an overview of exception handling in Java, detailing types of errors (compile-time and runtime) and exceptions (checked and unchecked). It explains the mechanisms for handling exceptions, including try-catch blocks, finally blocks, and custom exceptions, along with examples of built-in exceptions. Additionally, it describes how to create user-defined exceptions by extending the Exception class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Unit 3 : Exception Handling and Multithreading - 12 Marks

Exception Handling

Errors and Exception:​

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 is an unusual condition that can occur in the program. This


condition is caused due to run time error in the program.
Type of Exception:
1.​Checked Exception: All the exceptions other than the runtime
Exception are called as checked exceptions. The compiler checks them
during compilation.
2.​Unchecked Exception: Runtime exceptions are also known as unchecked
exceptions. These exceptions are not checked during compilation,
hence a programmer has to handle such kinds of exceptions.

Exception Handling:

Exception handling in Java allows developers to manage runtime


errors effectively by using mechanisms like try-catch block, finally
block, throwing Exceptions, Custom Exception handling, etc.

try: Program statements that you want to monitor for exceptions are
contained within a try block. If an exception occurs within the try
block, it is thrown.
Syntax: try {
// block of code to monitor for errors
}

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

finally: finally block is a block that is used to execute important


code such as closing connection, stream etc. Java finally block is
always executed whether exception is handled or not. Java finally
block follows try or catch block.
Syntax: finally {
// block of code to be executed before try block ends
}

Built-in Exceptions in Java



Built-in exceptions are exceptions that are predefined in the Java
libraries.​
These exceptions are designed to handle common errors and abnormal
situations that arise while running Java programs.
Java provides a rich set of built-in exception classes, most of which are
part of the java.lang package. These exceptions make it easier to catch
and handle errors without manually checking for all possible problems.

Below are some commonly used built-in exceptions:

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"

Creating Own Exception Subclass

1.​Java allows you to create user defined exceptions by extending the


Exception class.
2.​This is useful when a user wants to define their own error
conditions.
3.​We can throw our own exception using the throw keyword.
4.​Syntax:
throw new ExceptionSubclass();

Steps:

1.​Create a class which extends Exception class.


2.​Write a constructor to accept error message.
3.​Create an object and throw it using throw.
4.​Catch it using a try-catch block.

Example:

class MyException extends Exception {


MyException(String msg) {
super(msg);
}
}

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);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy