0% found this document useful (0 votes)
4 views6 pages

Exception Handling

Uploaded by

sundarmatsa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

Exception Handling

Uploaded by

sundarmatsa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Exception

Handling
in Java
- S I VA J I L AV E T I
Introduction to Exception
Handling
1.What is an Exception ?

In programming an exception is an unexpected event that occurs during the execution of a


program, disrupting its normal flow.

2. What is Exception Handling?


• Mechanism to handle runtime errors.
• Ensures program continues to run smoothly.

Handling exception using try catch and throws


What is try-catch?
•try Block: public class Example {
public static void main(String[] args) {
•Used to write code that may throw an exception try{
. int data = 50 / 0; // ThrowArithmeticException
•catch Block: } catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
•Handles the exception if it occurs. }
Syntax: System.out.println("Program continues...");
try { }
// Code that may throw an }
exception
} catch (ExceptionType e) {
// Handling the exception
}
What is throws?

• Throws
•Used to indicate what exception type may be thrown by a
method

• throw
•Used to throw an exception for a method

Syntax:
void methodName() throws
ExceptionType {
// code
}
// Main method propagates the exception

public static void main(String[] args) throws


InvalidAgeException {

// Direct call without try-catch

validateAge(16); // Throws exception

System.out.println("Program ends successfully.");

} class InvalidAgeException extends Exception


{
} public InvalidAgeException(String
public class CustomExceptionExample { message) {
super(message);
// Method declares that it throws InvalidAgeException }
static void validateAge(int age) throws InvalidAgeException
}
{

if (age < 18) {

throw new InvalidAgeException("Age must be 18 or


above.");

} else {

System.out.println("Valid age.");

You might also like