Found 9150 Articles for Object Oriented Programming

Can a method throw java.lang.Exception without declaring it in java?

Maruthi Krishna
Updated on 06-Aug-2019 11:39:12

230 Views

No, for that matter to throw any exception explicitly you need to create an object of that exception and throw it using the throw keyword.Without creating an object you cannot throw an exception explicitly, you might create a scenario that causes the respective exception.ExampleFollowing Java program throws a NullPointerExceptionpublic class ExceptionExample {    public static void main(String[] args) {       System.out.println("Hello");       NullPointerException nullPointer = new NullPointerException();       throw nullPointer;    } }OutputHello Exception in thread "main" java.lang.NullPointerException    at MyPackage.ExceptionExample.main(ExceptionExample.java:6)

How can I add condition in custom exceptions in java?

Maruthi Krishna
Updated on 06-Aug-2019 11:37:29

729 Views

While reading values from the user in the constructor or any method you can validate those values using if condition.ExampleIn the following Java example we are defining two custom exception classes verifying name and age.import java.util.Scanner; class NotProperAgeException extends Throwable{    NotProperAgeException(String msg){       super(msg);    } } class NotProperNameException extends Throwable{    NotProperNameException(String msg){       super(msg);    } } public class CustomException{    private String name;    private int age;    public static boolean containsAlphabet(String name) {       for (int i = 0; i < name.length(); i++) {          char ch = name.charAt(i);          if (!(ch >= 'a' && ch

How to loop the program after an exception is thrown in java?

Maruthi Krishna
Updated on 06-Aug-2019 11:33:47

3K+ Views

Read the inputs and perform the required calculations within a method. Keep the code that causes exception in try block and catch all the possible exceptions in catch block(s). In each catch block display the respective message and call the method again.ExampleIn the following example we have an array with 5 elements, we are accepting two integers from user representing positions in the array and performing division operation with them, if the integer entered representing the positions is more than 5 (length of the exception) an ArrayIndexOutOfBoundsException occurs and, if the position chosen for denominator is 4 which is 0 ... Read More

How to print custom message instead of ErrorStackTrace in java?

Maruthi Krishna
Updated on 02-Jul-2020 15:03:02

4K+ Views

An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.Printing the Exception messageYou can print the exception message in Java using one of the following methods which are inherited from Throwable class.printStackTrace() − This method prints the backtrace to the standard error stream.getMessage() − This method returns the detail message string of the current throwable object.toString() − This message prints the short description of the current throwable object.Exampleimport java.util.Scanner; public class PrintingExceptionMessage { ... Read More

When does a Java Array Throws a NullPointerException?

Maruthi Krishna
Updated on 02-Jul-2020 14:40:03

4K+ Views

In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method.Object obj = null;But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.Examplepublic class Demo {    String name = "Krishna";    int age = 25;    public static void main(String args[]) {       ... Read More

Why can I throw null in Java and why does it upcast to a NullPointerException?

Maruthi Krishna
Updated on 02-Jul-2020 14:42:59

1K+ Views

In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method.Object obj = null;But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.Examplepublic class Demo {    String name = "Krishna";    int age = 25;    public static void main(String args[]) {       ... Read More

When do IllegalStateException and IllegalArgumentException get thrown? in java?

Maruthi Krishna
Updated on 06-Aug-2019 11:11:11

2K+ Views

IllegalStateException:This exception is thrown when you call a method at illegal or inappropriate time an IlleagalStateException is generated.For example, the remove() method of the ArrayList class removes the last element after calling the next() or previous methods.After removing the element at the current position you need to move to the next element to remove it i.e. per one call of the next() method you can invoke this remove() method only once.Since the initial position of the list (pointer) will be before the first element, you cannot invoke this method without calling the next method.If you invoke the remove() method otherwise ... Read More

How IllegalArgumentException automatically handled inside 'if' condition in java?

Maruthi Krishna
Updated on 02-Jul-2020 14:44:42

978 Views

Whenever you pass inappropriate arguments to a method or constructor, an IllegalArgumentException is thrown. It is a Runtime exception therefore there is no need to handle this at the time of compilation.ExampleThe valueOf() method of the java.sql.Date class accepts a String representing a date in JDBC escape format yyyy-[m]m-[d]d and converts it into a java.sql.Date object.import java.sql.Date; import java.util.Scanner; public class IllegalArgumentExample {    public static void main(String args[]) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter your date of birth in JDBC escape format (yyyy-mm-dd) ");       String dateString = sc.next();   ... Read More

What is the difference between throw e and throw new Exception(e) in catch block in java?

Maruthi Krishna
Updated on 02-Jul-2020 14:46:36

6K+ Views

An exception is an issue (run time error) occurred during the execution of a program. Here are some example scenarios −If you have an array of size 10 if a line in your code tries to access the 11th element in this array.If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to valuate it).When exception occurs the program terminates abruptly at the line that caused exception, leaving the remaining part of the program unexecuted. To prevent this, you need to handle exceptions.There are two types of exceptions in java.Unchecked Exception ... Read More

Handling IllegalComponentStateException in java.

Maruthi Krishna
Updated on 06-Aug-2019 09:11:49

381 Views

It is the sub class of IllegalStateException, This indicates that AWT component is not in an appropriate state i.e. if you are working with components but, not using them properly leads to this exception. There are several scenarios where this exception occursExampleIn the following example we are trying to build a sample login form here after setting the visibility of the window to true, we are trying to set the location by platform true which is inappropriate.import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LoginDemo extends JFrame implements ActionListener {    JPanel panel;    JLabel user_label, password_label, message;    JTextField ... Read More

Advertisements