‏إظهار الرسائل ذات التسميات Exceptions. إظهار كافة الرسائل
‏إظهار الرسائل ذات التسميات Exceptions. إظهار كافة الرسائل

الثلاثاء، 28 ديسمبر 2021

Java UnknownHostException - Invalid Hostname for Server - How to Fix It?

1. Introduction

In this tutorial, We'll learn what is UnknownHostException and What is the cause to produce it. And also learn how to prevent it.  UnknownHostException is a common exception and will show the best ways to prevent this exception.

Hierarchy:

java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.rmi.RemoteException
java.rmi.UnknownHostException


2. When is the Exception Thrown?


UnknownHostException is thrown if and if only there was a problem with a domain name or mistake in typing. And also indicates that the IP Address of a website could not be determined.

السبت، 18 ديسمبر 2021

Java Finally Block: Does Finally Execute After Return?

1. Introduction


In this tutorial, You'll be learning core java concepts as part of exception handling "Java finally block when return statement is encountered"

This is a famous interview question "will finally block is executed after return statement".
Answer is Yes, The finally block is executed even after a return statement in the method. So, finally block will always be executed even whether an exception is raised or not in java.

Finally Block: Will a finally block execute after a return statement in a method in Java?


We will look into the following in this article.
  • Finally block is executed right after try or catch blocks.
  • Scenarios where finally() block not executed
  • Does finally block Override the values returned by the try-catch block?
  • When happens to finally block execution if System.exit(1) is invoked?

الأربعاء، 8 ديسمبر 2021

الأربعاء، 1 ديسمبر 2021

Java - Creating Custom Exception

1. Overview

In this article, We'll learn how to create custom exceptions in java.

We'll show how to define user defined exceptions and how can be used as both checked and unchecked custom exceptions with examples.

First, we will understand the use of custom exceptions and then how to implement custom checked, unchecked exceptions.

Java - Creating Custom Exception


Java 8 IllegalStateException “Stream has already been operated upon or closed” Exception (Stream reuse)

1. Overview

In this short tutorial, We'll see the most common exception "java.lang.IllegalStateException: stream has already been operated upon or closed". We may encounter this exception when working with the Stream interface in Java 8.

Can we collect stream twice after closing?
Java Stream reuse – traverse stream multiple times?




stream has already been operated upon or closed

Exception

java.lang.IllegalStateException: stream has already been operated upon or closed

الاثنين، 15 نوفمبر 2021

Java - How to Solve IllegalArgumentException?

1. Overview

In this tutorial, We'll learn when IllegalArgumentException is thrown and how to solve IllegalArgumentException in java 8 programming.

This is a very common exception thrown by the java runtime for any invalid inputs. IllegalArgumentException is part of java.lang package and this is an unchecked exception.

IllegalArgumentException is extensively used in java api development and used by many classes even in java 8 stream api.

First, we will see when we get IllegalArgumentException in java with examples and next will understand how to troubleshoot and solve this problem?

Java - How to Solve IllegalArgumentException?


2. Java.lang.IllegalArgumentException Simulation

In the below example, first crated the ArrayList instance and added few string values to it. 

package com.javaprogramto.exception.IllegalArgumentException;

import java.util.ArrayList;
import java.util.List;

public class IllegalArgumentExceptionExample {

	public static void main(String[] args) {
		
		// Example 1
		List<String> list = new ArrayList<>(-10);
		list.add("a");
		list.add("b");
		list.add("c");
	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal Capacity: -10
	at java.base/java.util.ArrayList.<init>(ArrayList.java:160)
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:11)

From the above output, we could see the illegal argument exception while creating the ArrayList instance.

Few other java api including java 8 stream api and custom exceptions.

3. Java IllegalArgumentException Simulation using Java 8 stream api

Java 8 stream api has the skip() method which is used to skip the first n objects of the stream.

public class IllegalArgumentExceptionExample2 {

	public static void main(String[] args) {
		
		// Example 2
		List<String> stringsList = new ArrayList<>();
		stringsList.add("a");
		stringsList.add("b");
		stringsList.add("c");
		
		stringsList.stream().skip(-100);
	}
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: -100
	at java.base/java.util.stream.ReferencePipeline.skip(ReferencePipeline.java:476)
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample2.main(IllegalArgumentExceptionExample2.java:16)

4. Java IllegalArgumentException - throwing from custom condition

In the below code, we are checking the employee age that should be in between 18 and 65. The remaining age groups are not allowed for any job.

Now, if we get the employee object below 18 or above 65 then we need to reject the employee request.

So, we will use the illegal argument exception to throw the error.

import com.javaprogramto.java8.compare.Employee;

public class IllegalArgumentExceptionExample3 {

	public static void main(String[] args) {

		// Example 3
		Employee employeeRequest = new Employee(222, "Ram", 17);

		if (employeeRequest.getAge() < 18 || employeeRequest.getAge() > 65) {
			throw new IllegalArgumentException("Invalid age for the emp req");
		}

	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid age for the emp req
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample3.main(IllegalArgumentExceptionExample3.java:13)

5. Solving IllegalArgumentException in Java

After seeing the few examples on IllegalArgumentException, you might have got an understanding on when it is thrown by the API or custom conditions based.

IllegalArgumentException is thrown only if any one or more method arguments are not in its range. That means values are not passed correctly.

If IllegalArgumentException is thrown by the java api methods then to solve, you need to look at the error stack trace for the exact location of the file and line number.

To solve IllegalArgumentException, we need to correct method values passed to it. But, in some cases it is completely valid to throw this exception by the programmers for the specific conditions. In this case, we use it as validations with the proper error message.

Below code is the solution for all java api methods. But for the condition based, you can wrap it inside try/catch block. But this is not recommended.

package com.javaprogramto.exception.IllegalArgumentException;

import java.util.ArrayList;
import java.util.List;

import com.javaprogramto.java8.compare.Employee;

public class IllegalArgumentExceptionExample4 {

	public static void main(String[] args) {

		// Example 1
		List<String> list = new ArrayList<>(10);
		list.add("a");
		list.add("b");
		list.add("c");

		// Example 2
		List<String> stringsList = new ArrayList<>();
		stringsList.add("a");
		stringsList.add("b");
		stringsList.add("c");

		stringsList.stream().skip(2);

		// Example 3
		Employee employeeRequest = new Employee(222, "Ram", 20);

		if (employeeRequest.getAge() < 18 || employeeRequest.getAge() > 65) {
			throw new IllegalArgumentException("Invalid age for the emp req");
		}
		
		System.out.println("No errors");

	}
}


Output:

No errors

6. Conclusion

In this article, We've seen how to solve IllegalArgumentException in java.

GitHub

IllegalArgumentException

الأربعاء، 27 مارس 2019

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '-', = '#', = '.' - Solution

UnknownFormatConversionException in Java. 

In this post, We will learn about UnknownFormatConversionException with some examples and common exception "Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '-', = '#', = '.' - Solution".

Unchecked exception thrown when an unknown conversion is given

Unless otherwise specified, passing a null argument to any method or constructor in this class will cause a NullPointerException to be thrown.

NullPointerException in String contains method.

UnknownFormatConversionException is child class of IllegalFormatException class.


UnknownFormatConversionException


UnknownFormatConversionException Constructor Syntax:

public UnknownFormatConversionException(String s)


Constructs an instance of this class with the unknown conversion. s indicates the unknown conversion type or value.